1#!/usr/bin/env perl
2# SPDX-License-Identifier: GPL-2.0
3#
4# (c) 2001, Dave Jones. (the file handling bit)
5# (c) 2005, Joel Schopp <jschopp@austin.ibm.com> (the ugly bit)
6# (c) 2007,2008, Andy Whitcroft <apw@uk.ibm.com> (new conditions, test suite)
7# (c) 2008-2010 Andy Whitcroft <apw@canonical.com>
8# (c) 2010-2018 Joe Perches <joe@perches.com>
9
10use strict;
11use warnings;
12use POSIX;
13use File::Basename;
14use Cwd 'abs_path';
15use Term::ANSIColor qw(:constants);
16use Encode qw(decode encode);
17
18my $P = $0;
19my $D = dirname(abs_path($P));
20
21my $V = '0.32';
22
23use Getopt::Long qw(:config no_auto_abbrev);
24
25my $SOF = 1; # enables SOF-specific behaviour
26my $quiet = 0;
27my $tree = 1;
28my $chk_signoff = 1;
29my $chk_patch = 1;
30my $tst_only;
31my $emacs = 0;
32my $terse = 0;
33my $showfile = 0;
34my $file = 0;
35my $git = 0;
36my %git_commits = ();
37my $check = 0;
38my $check_orig = 0;
39my $summary = 1;
40my $mailback = 0;
41my $summary_file = 0;
42my $show_types = 0;
43my $list_types = 0;
44my $fix = 0;
45my $fix_inplace = 0;
46my $root;
47my %debug;
48my %camelcase = ();
49my %use_type = ();
50my @use = ();
51my %ignore_type = ();
52my @ignore = ();
53my $help = 0;
54my $configuration_file = ".checkpatch.conf";
55my $max_line_length = 100;
56my $ignore_perl_version = 0;
57my $minimum_perl_version = 5.10.0;
58my $min_conf_desc_length = 4;
59my $spelling_file = "$D/spelling.txt";
60my $codespell = 0;
61my $codespellfile = "/usr/share/codespell/dictionary.txt";
62my $conststructsfile = "$D/const_structs.checkpatch";
63my $typedefsfile = "";
64my $color = "auto";
65my $allow_c99_comments = 1; # Can be overridden by --ignore C99_COMMENT_TOLERANCE
66# git output parsing needs US English output, so first set backtick child process LANGUAGE
67my $git_command ='export LANGUAGE=en_US.UTF-8; git';
68
69sub help {
70	my ($exitcode) = @_;
71
72	print << "EOM";
73Usage: $P [OPTION]... [FILE]...
74Version: $V
75
76Options:
77  -q, --quiet                quiet
78  --no-tree                  run without a kernel tree
79  --no-signoff               do not check for 'Signed-off-by' line
80  --patch                    treat FILE as patchfile (default)
81  --emacs                    emacs compile window format
82  --terse                    one line per report
83  --showfile                 emit diffed file position, not input file position
84  -g, --git                  treat FILE as a single commit or git revision range
85                             single git commit with:
86                               <rev>
87                               <rev>^
88                               <rev>~n
89                             multiple git commits with:
90                               <rev1>..<rev2>
91                               <rev1>...<rev2>
92                               <rev>-<count>
93                             git merges are ignored
94  -f, --file                 treat FILE as regular source file
95  --subjective, --strict     enable more subjective tests
96  --list-types               list the possible message types
97  --types TYPE(,TYPE2...)    show only these comma separated message types
98  --ignore TYPE(,TYPE2...)   ignore various comma separated message types
99  --show-types               show the specific message type in the output
100  --max-line-length=n        set the maximum line length, (default $max_line_length)
101                             if exceeded, warn on patches
102                             requires --strict for use with --file
103  --min-conf-desc-length=n   set the min description length, if shorter, warn
104  --root=PATH                PATH to the kernel tree root
105  --no-summary               suppress the per-file summary
106  --mailback                 only produce a report in case of warnings/errors
107  --summary-file             include the filename in summary
108  --debug KEY=[0|1]          turn on/off debugging of KEY, where KEY is one of
109                             'values', 'possible', 'type', and 'attr' (default
110                             is all off)
111  --test-only=WORD           report only warnings/errors containing WORD
112                             literally
113  --fix                      EXPERIMENTAL - may create horrible results
114                             If correctable single-line errors exist, create
115                             "<inputfile>.EXPERIMENTAL-checkpatch-fixes"
116                             with potential errors corrected to the preferred
117                             checkpatch style
118  --fix-inplace              EXPERIMENTAL - may create horrible results
119                             Is the same as --fix, but overwrites the input
120                             file.  It's your fault if there's no backup or git
121  --ignore-perl-version      override checking of perl version.  expect
122                             runtime errors.
123  --codespell                Use the codespell dictionary for spelling/typos
124                             (default:/usr/share/codespell/dictionary.txt)
125  --codespellfile            Use this codespell dictionary
126  --typedefsfile             Read additional types from this file
127  --color[=WHEN]             Use colors 'always', 'never', or only when output
128                             is a terminal ('auto'). Default is 'auto'.
129  -h, --help, --version      display this help and exit
130
131When FILE is - read standard input.
132EOM
133
134	exit($exitcode);
135}
136
137sub uniq {
138	my %seen;
139	return grep { !$seen{$_}++ } @_;
140}
141
142sub list_types {
143	my ($exitcode) = @_;
144
145	my $count = 0;
146
147	local $/ = undef;
148
149	open(my $script, '<', abs_path($P)) or
150	    die "$P: Can't read '$P' $!\n";
151
152	my $text = <$script>;
153	close($script);
154
155	my @types = ();
156	# Also catch when type or level is passed through a variable
157	for ($text =~ /(?:(?:\bCHK|\bWARN|\bERROR|&\{\$msg_level})\s*\(|\$msg_type\s*=)\s*"([^"]+)"/g) {
158		push (@types, $_);
159	}
160	@types = sort(uniq(@types));
161	print("#\tMessage type\n\n");
162	foreach my $type (@types) {
163		print(++$count . "\t" . $type . "\n");
164	}
165
166	exit($exitcode);
167}
168
169my $conf = which_conf($configuration_file);
170if (-f $conf) {
171	my @conf_args;
172	open(my $conffile, '<', "$conf")
173	    or warn "$P: Can't find a readable $configuration_file file $!\n";
174
175	while (<$conffile>) {
176		my $line = $_;
177
178		$line =~ s/\s*\n?$//g;
179		$line =~ s/^\s*//g;
180		$line =~ s/\s+/ /g;
181
182		next if ($line =~ m/^\s*#/);
183		next if ($line =~ m/^\s*$/);
184
185		my @words = split(" ", $line);
186		foreach my $word (@words) {
187			last if ($word =~ m/^#/);
188			push (@conf_args, $word);
189		}
190	}
191	close($conffile);
192	unshift(@ARGV, @conf_args) if @conf_args;
193}
194
195# Perl's Getopt::Long allows options to take optional arguments after a space.
196# Prevent --color by itself from consuming other arguments
197foreach (@ARGV) {
198	if ($_ eq "--color" || $_ eq "-color") {
199		$_ = "--color=$color";
200	}
201}
202
203GetOptions(
204	'q|quiet+'	=> \$quiet,
205	'tree!'		=> \$tree,
206	'signoff!'	=> \$chk_signoff,
207	'patch!'	=> \$chk_patch,
208	'emacs!'	=> \$emacs,
209	'terse!'	=> \$terse,
210	'showfile!'	=> \$showfile,
211	'f|file!'	=> \$file,
212	'g|git!'	=> \$git,
213	'subjective!'	=> \$check,
214	'strict!'	=> \$check,
215	'ignore=s'	=> \@ignore,
216	'types=s'	=> \@use,
217	'show-types!'	=> \$show_types,
218	'list-types!'	=> \$list_types,
219	'max-line-length=i' => \$max_line_length,
220	'min-conf-desc-length=i' => \$min_conf_desc_length,
221	'root=s'	=> \$root,
222	'summary!'	=> \$summary,
223	'mailback!'	=> \$mailback,
224	'summary-file!'	=> \$summary_file,
225	'fix!'		=> \$fix,
226	'fix-inplace!'	=> \$fix_inplace,
227	'ignore-perl-version!' => \$ignore_perl_version,
228	'debug=s'	=> \%debug,
229	'test-only=s'	=> \$tst_only,
230	'codespell!'	=> \$codespell,
231	'codespellfile=s'	=> \$codespellfile,
232	'typedefsfile=s'	=> \$typedefsfile,
233	'color=s'	=> \$color,
234	'no-color'	=> \$color,	#keep old behaviors of -nocolor
235	'nocolor'	=> \$color,	#keep old behaviors of -nocolor
236	'h|help'	=> \$help,
237	'version'	=> \$help
238) or help(1);
239
240help(0) if ($help);
241
242list_types(0) if ($list_types);
243
244$fix = 1 if ($fix_inplace);
245$check_orig = $check;
246
247my $exit = 0;
248
249my $perl_version_ok = 1;
250if ($^V && $^V lt $minimum_perl_version) {
251	$perl_version_ok = 0;
252	printf "$P: requires at least perl version %vd\n", $minimum_perl_version;
253	exit(1) if (!$ignore_perl_version);
254}
255
256#if no filenames are given, push '-' to read patch from stdin
257if ($#ARGV < 0) {
258	push(@ARGV, '-');
259}
260
261if ($color =~ /^[01]$/) {
262	$color = !$color;
263} elsif ($color =~ /^always$/i) {
264	$color = 1;
265} elsif ($color =~ /^never$/i) {
266	$color = 0;
267} elsif ($color =~ /^auto$/i) {
268	$color = (-t STDOUT);
269} else {
270	die "Invalid color mode: $color\n";
271}
272
273sub hash_save_array_words {
274	my ($hashRef, $arrayRef) = @_;
275
276	my @array = split(/,/, join(',', @$arrayRef));
277	foreach my $word (@array) {
278		$word =~ s/\s*\n?$//g;
279		$word =~ s/^\s*//g;
280		$word =~ s/\s+/ /g;
281		$word =~ tr/[a-z]/[A-Z]/;
282
283		next if ($word =~ m/^\s*#/);
284		next if ($word =~ m/^\s*$/);
285
286		$hashRef->{$word}++;
287	}
288}
289
290sub hash_show_words {
291	my ($hashRef, $prefix) = @_;
292
293	if (keys %$hashRef) {
294		print "\nNOTE: $prefix message types:";
295		foreach my $word (sort keys %$hashRef) {
296			print " $word";
297		}
298		print "\n";
299	}
300}
301
302hash_save_array_words(\%ignore_type, \@ignore);
303hash_save_array_words(\%use_type, \@use);
304
305my $dbg_values = 0;
306my $dbg_possible = 0;
307my $dbg_type = 0;
308my $dbg_attr = 0;
309for my $key (keys %debug) {
310	## no critic
311	eval "\${dbg_$key} = '$debug{$key}';";
312	die "$@" if ($@);
313}
314
315my $rpt_cleaners = 0;
316
317if ($terse) {
318	$emacs = 1;
319	$quiet++;
320}
321
322if ($tree) {
323	if (defined $root) {
324		if (!top_of_kernel_tree($root)) {
325			die "$P: $root: --root does not point at a valid tree\n";
326		}
327	} else {
328		if (top_of_kernel_tree('.')) {
329			$root = '.';
330		} elsif ($0 =~ m@(.*)/scripts/[^/]*$@ &&
331						top_of_kernel_tree($1)) {
332			$root = $1;
333		}
334	}
335
336	if (!defined $root) {
337		print "Must be run from the top-level dir. of a kernel tree\n";
338		exit(2);
339	}
340}
341
342my $emitted_corrupt = 0;
343
344our $Ident	= qr{
345			[A-Za-z_][A-Za-z\d_]*
346			(?:\s*\#\#\s*[A-Za-z_][A-Za-z\d_]*)*
347		}x;
348our $Storage	= qr{extern|static|asmlinkage};
349our $Sparse	= qr{
350			__user|
351			__kernel|
352			__force|
353			__iomem|
354			__must_check|
355			__kprobes|
356			__ref|
357			__refconst|
358			__refdata|
359			__rcu|
360			__private
361		}x;
362our $InitAttributePrefix = qr{__(?:mem|cpu|dev|net_|)};
363our $InitAttributeData = qr{$InitAttributePrefix(?:initdata\b)};
364our $InitAttributeConst = qr{$InitAttributePrefix(?:initconst\b)};
365our $InitAttributeInit = qr{$InitAttributePrefix(?:init\b)};
366our $InitAttribute = qr{$InitAttributeData|$InitAttributeConst|$InitAttributeInit};
367
368# Notes to $Attribute:
369# We need \b after 'init' otherwise 'initconst' will cause a false positive in a check
370our $Attribute	= qr{
371			const|
372			__percpu|
373			__nocast|
374			__safe|
375			__bitwise|
376			__packed__|
377			__packed2__|
378			__naked|
379			__maybe_unused|
380			__always_unused|
381			__noreturn|
382			__used|
383			__cold|
384			__pure|
385			__noclone|
386			__deprecated|
387			__read_mostly|
388			__ro_after_init|
389			__kprobes|
390			$InitAttribute|
391			____cacheline_aligned|
392			____cacheline_aligned_in_smp|
393			____cacheline_internodealigned_in_smp|
394			__weak
395		  }x;
396our $Modifier;
397our $Inline	= qr{inline|__always_inline|noinline|__inline|__inline__};
398our $Member	= qr{->$Ident|\.$Ident|\[[^]]*\]};
399our $Lval	= qr{$Ident(?:$Member)*};
400
401our $Int_type	= qr{(?i)llu|ull|ll|lu|ul|l|u};
402our $Binary	= qr{(?i)0b[01]+$Int_type?};
403our $Hex	= qr{(?i)0x[0-9a-f]+$Int_type?};
404our $Int	= qr{[0-9]+$Int_type?};
405our $Octal	= qr{0[0-7]+$Int_type?};
406our $String	= qr{"[X\t]*"};
407our $Float_hex	= qr{(?i)0x[0-9a-f]+p-?[0-9]+[fl]?};
408our $Float_dec	= qr{(?i)(?:[0-9]+\.[0-9]*|[0-9]*\.[0-9]+)(?:e-?[0-9]+)?[fl]?};
409our $Float_int	= qr{(?i)[0-9]+e-?[0-9]+[fl]?};
410our $Float	= qr{$Float_hex|$Float_dec|$Float_int};
411our $Constant	= qr{$Float|$Binary|$Octal|$Hex|$Int};
412our $Assignment	= qr{\*\=|/=|%=|\+=|-=|<<=|>>=|&=|\^=|\|=|=};
413our $Compare    = qr{<=|>=|==|!=|<|(?<!-)>};
414our $Arithmetic = qr{\+|-|\*|\/|%};
415our $Operators	= qr{
416			<=|>=|==|!=|
417			=>|->|<<|>>|<|>|!|~|
418			&&|\|\||,|\^|\+\+|--|&|\||$Arithmetic
419		  }x;
420
421our $c90_Keywords = qr{do|for|while|if|else|return|goto|continue|switch|default|case|break}x;
422
423our $BasicType;
424our $NonptrType;
425our $NonptrTypeMisordered;
426our $NonptrTypeWithAttr;
427our $Type;
428our $TypeMisordered;
429our $Declare;
430our $DeclareMisordered;
431
432our $NON_ASCII_UTF8	= qr{
433	[\xC2-\xDF][\x80-\xBF]               # non-overlong 2-byte
434	|  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
435	| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
436	|  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
437	|  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
438	| [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
439	|  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
440}x;
441
442our $UTF8	= qr{
443	[\x09\x0A\x0D\x20-\x7E]              # ASCII
444	| $NON_ASCII_UTF8
445}x;
446
447our $typeC99Typedefs = qr{(?:__)?(?:[us]_?)?int_?(?:8|16|32|64)_t};
448our $typeOtherOSTypedefs = qr{(?x:
449	u_(?:char|short|int|long) |          # bsd
450	u(?:nchar|short|int|long)            # sysv
451)};
452our $typeKernelTypedefs = qr{(?x:
453	(?:__)?(?:u|s|be|le)(?:8|16|32|64)|
454	atomic_t
455)};
456our $typeTypedefs = qr{(?x:
457	$typeC99Typedefs\b|
458	$typeOtherOSTypedefs\b|
459	$typeKernelTypedefs\b
460)};
461
462our $zero_initializer = qr{(?:(?:0[xX])?0+$Int_type?|NULL|false)\b};
463
464our $logFunctions = qr{(?x:
465	printk(?:_ratelimited|_once|_deferred_once|_deferred|)|
466	(?:[a-z0-9]+_){1,2}(?:printk|emerg|alert|crit|err|warning|warn|notice|info|debug|dbg|vdbg|devel|cont|WARN)(?:_ratelimited|_once|)|
467	TP_printk|
468	WARN(?:_RATELIMIT|_ONCE|)|
469	panic|
470	MODULE_[A-Z_]+|
471	seq_vprintf|seq_printf|seq_puts|
472	trace[a-z_]+
473)};
474
475our $allocFunctions = qr{(?x:
476	(?:(?:devm_)?
477		(?:kv|k|v)[czm]alloc(?:_node|_array)? |
478		kstrdup(?:_const)? |
479		kmemdup(?:_nul)?) |
480	(?:\w+)?alloc_skb(?:ip_align)? |
481				# dev_alloc_skb/netdev_alloc_skb, et al
482	dma_alloc_coherent
483)};
484
485our $signature_tags = qr{(?xi:
486	Signed-off-by:|
487	Co-developed-by:|
488	Acked-by:|
489	Tested-by:|
490	Reviewed-by:|
491	Reported-by:|
492	Suggested-by:|
493	To:|
494	Cc:
495)};
496
497our @typeListMisordered = (
498	qr{char\s+(?:un)?signed},
499	qr{int\s+(?:(?:un)?signed\s+)?short\s},
500	qr{int\s+short(?:\s+(?:un)?signed)},
501	qr{short\s+int(?:\s+(?:un)?signed)},
502	qr{(?:un)?signed\s+int\s+short},
503	qr{short\s+(?:un)?signed},
504	qr{long\s+int\s+(?:un)?signed},
505	qr{int\s+long\s+(?:un)?signed},
506	qr{long\s+(?:un)?signed\s+int},
507	qr{int\s+(?:un)?signed\s+long},
508	qr{int\s+(?:un)?signed},
509	qr{int\s+long\s+long\s+(?:un)?signed},
510	qr{long\s+long\s+int\s+(?:un)?signed},
511	qr{long\s+long\s+(?:un)?signed\s+int},
512	qr{long\s+long\s+(?:un)?signed},
513	qr{long\s+(?:un)?signed},
514);
515
516our @typeList = (
517	qr{void},
518	qr{(?:(?:un)?signed\s+)?char},
519	qr{(?:(?:un)?signed\s+)?short\s+int},
520	qr{(?:(?:un)?signed\s+)?short},
521	qr{(?:(?:un)?signed\s+)?int},
522	qr{(?:(?:un)?signed\s+)?long\s+int},
523	qr{(?:(?:un)?signed\s+)?long\s+long\s+int},
524	qr{(?:(?:un)?signed\s+)?long\s+long},
525	qr{(?:(?:un)?signed\s+)?long},
526	qr{(?:un)?signed},
527	qr{float},
528	qr{double},
529	qr{bool},
530	qr{struct\s+$Ident},
531	qr{union\s+$Ident},
532	qr{enum\s+$Ident},
533	qr{${Ident}_t},
534	qr{${Ident}_handler},
535	qr{${Ident}_handler_fn},
536	@typeListMisordered,
537);
538
539our $C90_int_types = qr{(?x:
540	long\s+long\s+int\s+(?:un)?signed|
541	long\s+long\s+(?:un)?signed\s+int|
542	long\s+long\s+(?:un)?signed|
543	(?:(?:un)?signed\s+)?long\s+long\s+int|
544	(?:(?:un)?signed\s+)?long\s+long|
545	int\s+long\s+long\s+(?:un)?signed|
546	int\s+(?:(?:un)?signed\s+)?long\s+long|
547
548	long\s+int\s+(?:un)?signed|
549	long\s+(?:un)?signed\s+int|
550	long\s+(?:un)?signed|
551	(?:(?:un)?signed\s+)?long\s+int|
552	(?:(?:un)?signed\s+)?long|
553	int\s+long\s+(?:un)?signed|
554	int\s+(?:(?:un)?signed\s+)?long|
555
556	int\s+(?:un)?signed|
557	(?:(?:un)?signed\s+)?int
558)};
559
560our @typeListFile = ();
561our @typeListWithAttr = (
562	@typeList,
563	qr{struct\s+$InitAttribute\s+$Ident},
564	qr{union\s+$InitAttribute\s+$Ident},
565);
566
567our @modifierList = (
568	qr{fastcall},
569);
570our @modifierListFile = ();
571
572our @mode_permission_funcs = (
573	["module_param", 3],
574	["module_param_(?:array|named|string)", 4],
575	["module_param_array_named", 5],
576	["debugfs_create_(?:file|u8|u16|u32|u64|x8|x16|x32|x64|size_t|atomic_t|bool|blob|regset32|u32_array)", 2],
577	["proc_create(?:_data|)", 2],
578	["(?:CLASS|DEVICE|SENSOR|SENSOR_DEVICE|IIO_DEVICE)_ATTR", 2],
579	["IIO_DEV_ATTR_[A-Z_]+", 1],
580	["SENSOR_(?:DEVICE_|)ATTR_2", 2],
581	["SENSOR_TEMPLATE(?:_2|)", 3],
582	["__ATTR", 2],
583);
584
585#Create a search pattern for all these functions to speed up a loop below
586our $mode_perms_search = "";
587foreach my $entry (@mode_permission_funcs) {
588	$mode_perms_search .= '|' if ($mode_perms_search ne "");
589	$mode_perms_search .= $entry->[0];
590}
591$mode_perms_search = "(?:${mode_perms_search})";
592
593our %deprecated_apis = (
594	"synchronize_rcu_bh"			=> "synchronize_rcu",
595	"synchronize_rcu_bh_expedited"		=> "synchronize_rcu_expedited",
596	"call_rcu_bh"				=> "call_rcu",
597	"rcu_barrier_bh"			=> "rcu_barrier",
598	"synchronize_sched"			=> "synchronize_rcu",
599	"synchronize_sched_expedited"		=> "synchronize_rcu_expedited",
600	"call_rcu_sched"			=> "call_rcu",
601	"rcu_barrier_sched"			=> "rcu_barrier",
602	"get_state_synchronize_sched"		=> "get_state_synchronize_rcu",
603	"cond_synchronize_sched"		=> "cond_synchronize_rcu",
604);
605
606#Create a search pattern for all these strings to speed up a loop below
607our $deprecated_apis_search = "";
608foreach my $entry (keys %deprecated_apis) {
609	$deprecated_apis_search .= '|' if ($deprecated_apis_search ne "");
610	$deprecated_apis_search .= $entry;
611}
612$deprecated_apis_search = "(?:${deprecated_apis_search})";
613
614our $mode_perms_world_writable = qr{
615	S_IWUGO		|
616	S_IWOTH		|
617	S_IRWXUGO	|
618	S_IALLUGO	|
619	0[0-7][0-7][2367]
620}x;
621
622our %mode_permission_string_types = (
623	"S_IRWXU" => 0700,
624	"S_IRUSR" => 0400,
625	"S_IWUSR" => 0200,
626	"S_IXUSR" => 0100,
627	"S_IRWXG" => 0070,
628	"S_IRGRP" => 0040,
629	"S_IWGRP" => 0020,
630	"S_IXGRP" => 0010,
631	"S_IRWXO" => 0007,
632	"S_IROTH" => 0004,
633	"S_IWOTH" => 0002,
634	"S_IXOTH" => 0001,
635	"S_IRWXUGO" => 0777,
636	"S_IRUGO" => 0444,
637	"S_IWUGO" => 0222,
638	"S_IXUGO" => 0111,
639);
640
641#Create a search pattern for all these strings to speed up a loop below
642our $mode_perms_string_search = "";
643foreach my $entry (keys %mode_permission_string_types) {
644	$mode_perms_string_search .= '|' if ($mode_perms_string_search ne "");
645	$mode_perms_string_search .= $entry;
646}
647our $single_mode_perms_string_search = "(?:${mode_perms_string_search})";
648our $multi_mode_perms_string_search = qr{
649	${single_mode_perms_string_search}
650	(?:\s*\|\s*${single_mode_perms_string_search})*
651}x;
652
653sub perms_to_octal {
654	my ($string) = @_;
655
656	return trim($string) if ($string =~ /^\s*0[0-7]{3,3}\s*$/);
657
658	my $val = "";
659	my $oval = "";
660	my $to = 0;
661	my $curpos = 0;
662	my $lastpos = 0;
663	while ($string =~ /\b(($single_mode_perms_string_search)\b(?:\s*\|\s*)?\s*)/g) {
664		$curpos = pos($string);
665		my $match = $2;
666		my $omatch = $1;
667		last if ($lastpos > 0 && ($curpos - length($omatch) != $lastpos));
668		$lastpos = $curpos;
669		$to |= $mode_permission_string_types{$match};
670		$val .= '\s*\|\s*' if ($val ne "");
671		$val .= $match;
672		$oval .= $omatch;
673	}
674	$oval =~ s/^\s*\|\s*//;
675	$oval =~ s/\s*\|\s*$//;
676	return sprintf("%04o", $to);
677}
678
679our $allowed_asm_includes = qr{(?x:
680	irq|
681	memory|
682	time|
683	reboot
684)};
685# memory.h: ARM has a custom one
686
687# Load common spelling mistakes and build regular expression list.
688my $misspellings;
689my %spelling_fix;
690
691if (open(my $spelling, '<', $spelling_file)) {
692	while (<$spelling>) {
693		my $line = $_;
694
695		$line =~ s/\s*\n?$//g;
696		$line =~ s/^\s*//g;
697
698		next if ($line =~ m/^\s*#/);
699		next if ($line =~ m/^\s*$/);
700
701		my ($suspect, $fix) = split(/\|\|/, $line);
702
703		$spelling_fix{$suspect} = $fix;
704	}
705	close($spelling);
706} else {
707	warn "No typos will be found - file '$spelling_file': $!\n";
708}
709
710if ($codespell) {
711	if (open(my $spelling, '<', $codespellfile)) {
712		while (<$spelling>) {
713			my $line = $_;
714
715			$line =~ s/\s*\n?$//g;
716			$line =~ s/^\s*//g;
717
718			next if ($line =~ m/^\s*#/);
719			next if ($line =~ m/^\s*$/);
720			next if ($line =~ m/, disabled/i);
721
722			$line =~ s/,.*$//;
723
724			my ($suspect, $fix) = split(/->/, $line);
725
726			$spelling_fix{$suspect} = $fix;
727		}
728		close($spelling);
729	} else {
730		warn "No codespell typos will be found - file '$codespellfile': $!\n";
731	}
732}
733
734$misspellings = join("|", sort keys %spelling_fix) if keys %spelling_fix;
735
736sub read_words {
737	my ($wordsRef, $file) = @_;
738
739	if (open(my $words, '<', $file)) {
740		while (<$words>) {
741			my $line = $_;
742
743			$line =~ s/\s*\n?$//g;
744			$line =~ s/^\s*//g;
745
746			next if ($line =~ m/^\s*#/);
747			next if ($line =~ m/^\s*$/);
748			if ($line =~ /\s/) {
749				print("$file: '$line' invalid - ignored\n");
750				next;
751			}
752
753			$$wordsRef .= '|' if ($$wordsRef ne "");
754			$$wordsRef .= $line;
755		}
756		close($file);
757		return 1;
758	}
759
760	return 0;
761}
762
763my $const_structs = "";
764read_words(\$const_structs, $conststructsfile)
765    or warn "No structs that should be const will be found - file '$conststructsfile': $!\n";
766
767my $typeOtherTypedefs = "";
768if (length($typedefsfile)) {
769	read_words(\$typeOtherTypedefs, $typedefsfile)
770	    or warn "No additional types will be considered - file '$typedefsfile': $!\n";
771}
772$typeTypedefs .= '|' . $typeOtherTypedefs if ($typeOtherTypedefs ne "");
773
774sub build_types {
775	my $mods = "(?x:  \n" . join("|\n  ", (@modifierList, @modifierListFile)) . "\n)";
776	my $all = "(?x:  \n" . join("|\n  ", (@typeList, @typeListFile)) . "\n)";
777	my $Misordered = "(?x:  \n" . join("|\n  ", @typeListMisordered) . "\n)";
778	my $allWithAttr = "(?x:  \n" . join("|\n  ", @typeListWithAttr) . "\n)";
779	$Modifier	= qr{(?:$Attribute|$Sparse|$mods)};
780	$BasicType	= qr{
781				(?:$typeTypedefs\b)|
782				(?:${all}\b)
783		}x;
784	$NonptrType	= qr{
785			(?:$Modifier\s+|const\s+)*
786			(?:
787				(?:typeof|__typeof__)\s*\([^\)]*\)|
788				(?:$typeTypedefs\b)|
789				(?:${all}\b)
790			)
791			(?:\s+$Modifier|\s+const)*
792		  }x;
793	$NonptrTypeMisordered	= qr{
794			(?:$Modifier\s+|const\s+)*
795			(?:
796				(?:${Misordered}\b)
797			)
798			(?:\s+$Modifier|\s+const)*
799		  }x;
800	$NonptrTypeWithAttr	= qr{
801			(?:$Modifier\s+|const\s+)*
802			(?:
803				(?:typeof|__typeof__)\s*\([^\)]*\)|
804				(?:$typeTypedefs\b)|
805				(?:${allWithAttr}\b)
806			)
807			(?:\s+$Modifier|\s+const)*
808		  }x;
809	$Type	= qr{
810			$NonptrType
811			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
812			(?:\s+$Inline|\s+$Modifier)*
813		  }x;
814	$TypeMisordered	= qr{
815			$NonptrTypeMisordered
816			(?:(?:\s|\*|\[\])+\s*const|(?:\s|\*\s*(?:const\s*)?|\[\])+|(?:\s*\[\s*\])+)?
817			(?:\s+$Inline|\s+$Modifier)*
818		  }x;
819	$Declare	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$Type};
820	$DeclareMisordered	= qr{(?:$Storage\s+(?:$Inline\s+)?)?$TypeMisordered};
821}
822build_types();
823
824our $Typecast	= qr{\s*(\(\s*$NonptrType\s*\)){0,1}\s*};
825
826# Using $balanced_parens, $LvalOrFunc, or $FuncArg
827# requires at least perl version v5.10.0
828# Any use must be runtime checked with $^V
829
830our $balanced_parens = qr/(\((?:[^\(\)]++|(?-1))*\))/;
831our $LvalOrFunc	= qr{((?:[\&\*]\s*)?$Lval)\s*($balanced_parens{0,1})\s*};
832our $FuncArg = qr{$Typecast{0,1}($LvalOrFunc|$Constant|$String)};
833
834our $declaration_macros = qr{(?x:
835	(?:$Storage\s+)?(?:[A-Z_][A-Z0-9]*_){0,2}(?:DEFINE|DECLARE)(?:_[A-Z0-9]+){1,6}\s*\(|
836	(?:$Storage\s+)?[HLP]?LIST_HEAD\s*\(|
837	(?:$Storage\s+)?${Type}\s+uninitialized_var\s*\(|
838	(?:SKCIPHER_REQUEST|SHASH_DESC|AHASH_REQUEST)_ON_STACK\s*\(
839)};
840
841sub deparenthesize {
842	my ($string) = @_;
843	return "" if (!defined($string));
844
845	while ($string =~ /^\s*\(.*\)\s*$/) {
846		$string =~ s@^\s*\(\s*@@;
847		$string =~ s@\s*\)\s*$@@;
848	}
849
850	$string =~ s@\s+@ @g;
851
852	return $string;
853}
854
855sub seed_camelcase_file {
856	my ($file) = @_;
857
858	return if (!(-f $file));
859
860	local $/;
861
862	open(my $include_file, '<', "$file")
863	    or warn "$P: Can't read '$file' $!\n";
864	my $text = <$include_file>;
865	close($include_file);
866
867	my @lines = split('\n', $text);
868
869	foreach my $line (@lines) {
870		next if ($line !~ /(?:[A-Z][a-z]|[a-z][A-Z])/);
871		if ($line =~ /^[ \t]*(?:#[ \t]*define|typedef\s+$Type)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)/) {
872			$camelcase{$1} = 1;
873		} elsif ($line =~ /^\s*$Declare\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[\(\[,;]/) {
874			$camelcase{$1} = 1;
875		} elsif ($line =~ /^\s*(?:union|struct|enum)\s+(\w*(?:[A-Z][a-z]|[a-z][A-Z])\w*)\s*[;\{]/) {
876			$camelcase{$1} = 1;
877		}
878	}
879}
880
881sub is_maintained_obsolete {
882	my ($filename) = @_;
883
884	return 0 if (!$tree || !(-e "$root/scripts/get_maintainer.pl"));
885
886	my $status = `perl $root/scripts/get_maintainer.pl --status --nom --nol --nogit --nogit-fallback -f $filename 2>&1`;
887
888	return $status =~ /obsolete/i;
889}
890
891sub is_SPDX_License_valid {
892	my ($license) = @_;
893
894	return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$root/.git"));
895
896	my $root_path = abs_path($root);
897	my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
898	return 0 if ($status ne "");
899	return 1;
900}
901
902my $camelcase_seeded = 0;
903sub seed_camelcase_includes {
904	return if ($camelcase_seeded);
905
906	my $files;
907	my $camelcase_cache = "";
908	my @include_files = ();
909
910	$camelcase_seeded = 1;
911
912	if (-e ".git") {
913		my $git_last_include_commit = `${git_command} log --no-merges --pretty=format:"%h%n" -1 -- include`;
914		chomp $git_last_include_commit;
915		$camelcase_cache = ".checkpatch-camelcase.git.$git_last_include_commit";
916	} else {
917		my $last_mod_date = 0;
918		$files = `find $root/include -name "*.h"`;
919		@include_files = split('\n', $files);
920		foreach my $file (@include_files) {
921			my $date = POSIX::strftime("%Y%m%d%H%M",
922						   localtime((stat $file)[9]));
923			$last_mod_date = $date if ($last_mod_date < $date);
924		}
925		$camelcase_cache = ".checkpatch-camelcase.date.$last_mod_date";
926	}
927
928	if ($camelcase_cache ne "" && -f $camelcase_cache) {
929		open(my $camelcase_file, '<', "$camelcase_cache")
930		    or warn "$P: Can't read '$camelcase_cache' $!\n";
931		while (<$camelcase_file>) {
932			chomp;
933			$camelcase{$_} = 1;
934		}
935		close($camelcase_file);
936
937		return;
938	}
939
940	if (-e ".git") {
941		$files = `${git_command} ls-files "include/*.h"`;
942		@include_files = split('\n', $files);
943	}
944
945	foreach my $file (@include_files) {
946		seed_camelcase_file($file);
947	}
948
949	if ($camelcase_cache ne "") {
950		unlink glob ".checkpatch-camelcase.*";
951		open(my $camelcase_file, '>', "$camelcase_cache")
952		    or warn "$P: Can't write '$camelcase_cache' $!\n";
953		foreach (sort { lc($a) cmp lc($b) } keys(%camelcase)) {
954			print $camelcase_file ("$_\n");
955		}
956		close($camelcase_file);
957	}
958}
959
960sub git_commit_info {
961	my ($commit, $id, $desc) = @_;
962
963	return ($id, $desc) if ((which("git") eq "") || !(-e ".git"));
964
965	my $output = `${git_command} log --no-color --format='%H %s' -1 $commit 2>&1`;
966	$output =~ s/^\s*//gm;
967	my @lines = split("\n", $output);
968
969	return ($id, $desc) if ($#lines < 0);
970
971	if ($lines[0] =~ /^error: short SHA1 $commit is ambiguous/) {
972# Maybe one day convert this block of bash into something that returns
973# all matching commit ids, but it's very slow...
974#
975#		echo "checking commits $1..."
976#		git rev-list --remotes | grep -i "^$1" |
977#		while read line ; do
978#		    git log --format='%H %s' -1 $line |
979#		    echo "commit $(cut -c 1-12,41-)"
980#		done
981	} elsif ($lines[0] =~ /^fatal: ambiguous argument '$commit': unknown revision or path not in the working tree\./) {
982		$id = undef;
983	} else {
984		$id = substr($lines[0], 0, 12);
985		$desc = substr($lines[0], 41);
986	}
987
988	return ($id, $desc);
989}
990
991$chk_signoff = 0 if ($file);
992
993my @rawlines = ();
994my @lines = ();
995my @fixed = ();
996my @fixed_inserted = ();
997my @fixed_deleted = ();
998my $fixlinenr = -1;
999
1000# If input is git commits, extract all commits from the commit expressions.
1001# For example, HEAD-3 means we need check 'HEAD, HEAD~1, HEAD~2'.
1002die "$P: No git repository found\n" if ($git && !-e ".git");
1003
1004if ($git) {
1005	my @commits = ();
1006	foreach my $commit_expr (@ARGV) {
1007		my $git_range;
1008		if ($commit_expr =~ m/^(.*)-(\d+)$/) {
1009			$git_range = "-$2 $1";
1010		} elsif ($commit_expr =~ m/\.\./) {
1011			$git_range = "$commit_expr";
1012		} else {
1013			$git_range = "-1 $commit_expr";
1014		}
1015		my $lines = `${git_command} log --no-color --no-merges --pretty=format:'%H %s' $git_range`;
1016		foreach my $line (split(/\n/, $lines)) {
1017			$line =~ /^([0-9a-fA-F]{40,40}) (.*)$/;
1018			next if (!defined($1) || !defined($2));
1019			my $sha1 = $1;
1020			my $subject = $2;
1021			unshift(@commits, $sha1);
1022			$git_commits{$sha1} = $subject;
1023		}
1024	}
1025	die "$P: no git commits after extraction!\n" if (@commits == 0);
1026	@ARGV = @commits;
1027}
1028
1029my $vname;
1030$allow_c99_comments = !defined $ignore_type{"C99_COMMENT_TOLERANCE"};
1031for my $filename (@ARGV) {
1032	my $FILE;
1033	if ($git) {
1034		open($FILE, '-|', "git format-patch -M --stdout -1 $filename") ||
1035			die "$P: $filename: git format-patch failed - $!\n";
1036	} elsif ($file) {
1037		open($FILE, '-|', "diff -u /dev/null $filename") ||
1038			die "$P: $filename: diff failed - $!\n";
1039	} elsif ($filename eq '-') {
1040		open($FILE, '<&STDIN');
1041	} else {
1042		open($FILE, '<', "$filename") ||
1043			die "$P: $filename: open failed - $!\n";
1044	}
1045	if ($filename eq '-') {
1046		$vname = 'Your patch';
1047	} elsif ($git) {
1048		$vname = "Commit " . substr($filename, 0, 12) . ' ("' . $git_commits{$filename} . '")';
1049	} else {
1050		$vname = $filename;
1051	}
1052	while (<$FILE>) {
1053		chomp;
1054		push(@rawlines, $_);
1055	}
1056	close($FILE);
1057
1058	if ($#ARGV > 0 && $quiet == 0) {
1059		print '-' x length($vname) . "\n";
1060		print "$vname\n";
1061		print '-' x length($vname) . "\n";
1062	}
1063
1064	if (!process($filename)) {
1065		$exit = 1;
1066	}
1067	@rawlines = ();
1068	@lines = ();
1069	@fixed = ();
1070	@fixed_inserted = ();
1071	@fixed_deleted = ();
1072	$fixlinenr = -1;
1073	@modifierListFile = ();
1074	@typeListFile = ();
1075	build_types();
1076}
1077
1078if (!$quiet) {
1079	hash_show_words(\%use_type, "Used");
1080	hash_show_words(\%ignore_type, "Ignored");
1081
1082	if (!$perl_version_ok) {
1083		print << "EOM"
1084
1085NOTE: perl $^V is not modern enough to detect all possible issues.
1086      An upgrade to at least perl $minimum_perl_version is suggested.
1087EOM
1088	}
1089	if ($exit) {
1090		print << "EOM"
1091
1092NOTE: If any of the errors are false positives, please report
1093      them to the maintainer, see CHECKPATCH in MAINTAINERS.
1094EOM
1095	}
1096}
1097
1098exit($exit);
1099
1100sub top_of_kernel_tree {
1101	my ($root) = @_;
1102
1103	my @tree_check = (
1104		"COPYING", "CREDITS", "Kbuild", "MAINTAINERS", "Makefile",
1105		"README", "Documentation", "arch", "include", "drivers",
1106		"fs", "init", "ipc", "kernel", "lib", "scripts",
1107	);
1108
1109	if ($SOF) {
1110		@tree_check = (
1111			"LICENCE", "README.md", "rimage", "tools",
1112			"scripts", "doc", "src", "CODEOWNERS",
1113			"CMakeLists.txt",
1114		);
1115	}
1116
1117	foreach my $check (@tree_check) {
1118		if (! -e $root . '/' . $check) {
1119			return 0;
1120		}
1121	}
1122	return 1;
1123}
1124
1125sub parse_email {
1126	my ($formatted_email) = @_;
1127
1128	my $name = "";
1129	my $address = "";
1130	my $comment = "";
1131
1132	if ($formatted_email =~ /^(.*)<(\S+\@\S+)>(.*)$/) {
1133		$name = $1;
1134		$address = $2;
1135		$comment = $3 if defined $3;
1136	} elsif ($formatted_email =~ /^\s*<(\S+\@\S+)>(.*)$/) {
1137		$address = $1;
1138		$comment = $2 if defined $2;
1139	} elsif ($formatted_email =~ /(\S+\@\S+)(.*)$/) {
1140		$address = $1;
1141		$comment = $2 if defined $2;
1142		$formatted_email =~ s/\Q$address\E.*$//;
1143		$name = $formatted_email;
1144		$name = trim($name);
1145		$name =~ s/^\"|\"$//g;
1146		# If there's a name left after stripping spaces and
1147		# leading quotes, and the address doesn't have both
1148		# leading and trailing angle brackets, the address
1149		# is invalid. ie:
1150		#   "joe smith joe@smith.com" bad
1151		#   "joe smith <joe@smith.com" bad
1152		if ($name ne "" && $address !~ /^<[^>]+>$/) {
1153			$name = "";
1154			$address = "";
1155			$comment = "";
1156		}
1157	}
1158
1159	$name = trim($name);
1160	$name =~ s/^\"|\"$//g;
1161	$address = trim($address);
1162	$address =~ s/^\<|\>$//g;
1163
1164	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1165		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1166		$name = "\"$name\"";
1167	}
1168
1169	return ($name, $address, $comment);
1170}
1171
1172sub format_email {
1173	my ($name, $address) = @_;
1174
1175	my $formatted_email;
1176
1177	$name = trim($name);
1178	$name =~ s/^\"|\"$//g;
1179	$address = trim($address);
1180
1181	if ($name =~ /[^\w \-]/i) { ##has "must quote" chars
1182		$name =~ s/(?<!\\)"/\\"/g; ##escape quotes
1183		$name = "\"$name\"";
1184	}
1185
1186	if ("$name" eq "") {
1187		$formatted_email = "$address";
1188	} else {
1189		$formatted_email = "$name <$address>";
1190	}
1191
1192	return $formatted_email;
1193}
1194
1195sub which {
1196	my ($bin) = @_;
1197
1198	foreach my $path (split(/:/, $ENV{PATH})) {
1199		if (-e "$path/$bin") {
1200			return "$path/$bin";
1201		}
1202	}
1203
1204	return "";
1205}
1206
1207sub which_conf {
1208	my ($conf) = @_;
1209
1210	foreach my $path (split(/:/, ".:$ENV{HOME}:.scripts")) {
1211		if (-e "$path/$conf") {
1212			return "$path/$conf";
1213		}
1214	}
1215
1216	return "";
1217}
1218
1219sub expand_tabs {
1220	my ($str) = @_;
1221
1222	my $res = '';
1223	my $n = 0;
1224	for my $c (split(//, $str)) {
1225		if ($c eq "\t") {
1226			$res .= ' ';
1227			$n++;
1228			for (; ($n % 8) != 0; $n++) {
1229				$res .= ' ';
1230			}
1231			next;
1232		}
1233		$res .= $c;
1234		$n++;
1235	}
1236
1237	return $res;
1238}
1239sub copy_spacing {
1240	(my $res = shift) =~ tr/\t/ /c;
1241	return $res;
1242}
1243
1244sub line_stats {
1245	my ($line) = @_;
1246
1247	# Drop the diff line leader and expand tabs
1248	$line =~ s/^.//;
1249	$line = expand_tabs($line);
1250
1251	# Pick the indent from the front of the line.
1252	my ($white) = ($line =~ /^(\s*)/);
1253
1254	return (length($line), length($white));
1255}
1256
1257my $sanitise_quote = '';
1258
1259sub sanitise_line_reset {
1260	my ($in_comment) = @_;
1261
1262	if ($in_comment) {
1263		$sanitise_quote = '*/';
1264	} else {
1265		$sanitise_quote = '';
1266	}
1267}
1268sub sanitise_line {
1269	my ($line) = @_;
1270
1271	my $res = '';
1272	my $l = '';
1273
1274	my $qlen = 0;
1275	my $off = 0;
1276	my $c;
1277
1278	# Always copy over the diff marker.
1279	$res = substr($line, 0, 1);
1280
1281	for ($off = 1; $off < length($line); $off++) {
1282		$c = substr($line, $off, 1);
1283
1284		# Comments we are whacking completely including the begin
1285		# and end, all to $;.
1286		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '/*') {
1287			$sanitise_quote = '*/';
1288
1289			substr($res, $off, 2, "$;$;");
1290			$off++;
1291			next;
1292		}
1293		if ($sanitise_quote eq '*/' && substr($line, $off, 2) eq '*/') {
1294			$sanitise_quote = '';
1295			substr($res, $off, 2, "$;$;");
1296			$off++;
1297			next;
1298		}
1299		if ($sanitise_quote eq '' && substr($line, $off, 2) eq '//') {
1300			$sanitise_quote = '//';
1301
1302			substr($res, $off, 2, $sanitise_quote);
1303			$off++;
1304			next;
1305		}
1306
1307		# A \ in a string means ignore the next character.
1308		if (($sanitise_quote eq "'" || $sanitise_quote eq '"') &&
1309		    $c eq "\\") {
1310			substr($res, $off, 2, 'XX');
1311			$off++;
1312			next;
1313		}
1314		# Regular quotes.
1315		if ($c eq "'" || $c eq '"') {
1316			if ($sanitise_quote eq '') {
1317				$sanitise_quote = $c;
1318
1319				substr($res, $off, 1, $c);
1320				next;
1321			} elsif ($sanitise_quote eq $c) {
1322				$sanitise_quote = '';
1323			}
1324		}
1325
1326		#print "c<$c> SQ<$sanitise_quote>\n";
1327		if ($off != 0 && $sanitise_quote eq '*/' && $c ne "\t") {
1328			substr($res, $off, 1, $;);
1329		} elsif ($off != 0 && $sanitise_quote eq '//' && $c ne "\t") {
1330			substr($res, $off, 1, $;);
1331		} elsif ($off != 0 && $sanitise_quote && $c ne "\t") {
1332			substr($res, $off, 1, 'X');
1333		} else {
1334			substr($res, $off, 1, $c);
1335		}
1336	}
1337
1338	if ($sanitise_quote eq '//') {
1339		$sanitise_quote = '';
1340	}
1341
1342	# The pathname on a #include may be surrounded by '<' and '>'.
1343	if ($res =~ /^.\s*\#\s*include\s+\<(.*)\>/) {
1344		my $clean = 'X' x length($1);
1345		$res =~ s@\<.*\>@<$clean>@;
1346
1347	# The whole of a #error is a string.
1348	} elsif ($res =~ /^.\s*\#\s*(?:error|warning)\s+(.*)\b/) {
1349		my $clean = 'X' x length($1);
1350		$res =~ s@(\#\s*(?:error|warning)\s+).*@$1$clean@;
1351	}
1352
1353	if ($allow_c99_comments && $res =~ m@(//.*$)@) {
1354		my $match = $1;
1355		$res =~ s/\Q$match\E/"$;" x length($match)/e;
1356	}
1357
1358	return $res;
1359}
1360
1361sub get_quoted_string {
1362	my ($line, $rawline) = @_;
1363
1364	return "" if (!defined($line) || !defined($rawline));
1365	return "" if ($line !~ m/($String)/g);
1366	return substr($rawline, $-[0], $+[0] - $-[0]);
1367}
1368
1369sub ctx_statement_block {
1370	my ($linenr, $remain, $off) = @_;
1371	my $line = $linenr - 1;
1372	my $blk = '';
1373	my $soff = $off;
1374	my $coff = $off - 1;
1375	my $coff_set = 0;
1376
1377	my $loff = 0;
1378
1379	my $type = '';
1380	my $level = 0;
1381	my @stack = ();
1382	my $p;
1383	my $c;
1384	my $len = 0;
1385
1386	my $remainder;
1387	while (1) {
1388		@stack = (['', 0]) if ($#stack == -1);
1389
1390		#warn "CSB: blk<$blk> remain<$remain>\n";
1391		# If we are about to drop off the end, pull in more
1392		# context.
1393		if ($off >= $len) {
1394			for (; $remain > 0; $line++) {
1395				last if (!defined $lines[$line]);
1396				next if ($lines[$line] =~ /^-/);
1397				$remain--;
1398				$loff = $len;
1399				$blk .= $lines[$line] . "\n";
1400				$len = length($blk);
1401				$line++;
1402				last;
1403			}
1404			# Bail if there is no further context.
1405			#warn "CSB: blk<$blk> off<$off> len<$len>\n";
1406			if ($off >= $len) {
1407				last;
1408			}
1409			if ($level == 0 && substr($blk, $off) =~ /^.\s*#\s*define/) {
1410				$level++;
1411				$type = '#';
1412			}
1413		}
1414		$p = $c;
1415		$c = substr($blk, $off, 1);
1416		$remainder = substr($blk, $off);
1417
1418		#warn "CSB: c<$c> type<$type> level<$level> remainder<$remainder> coff_set<$coff_set>\n";
1419
1420		# Handle nested #if/#else.
1421		if ($remainder =~ /^#\s*(?:ifndef|ifdef|if)\s/) {
1422			push(@stack, [ $type, $level ]);
1423		} elsif ($remainder =~ /^#\s*(?:else|elif)\b/) {
1424			($type, $level) = @{$stack[$#stack - 1]};
1425		} elsif ($remainder =~ /^#\s*endif\b/) {
1426			($type, $level) = @{pop(@stack)};
1427		}
1428
1429		# Statement ends at the ';' or a close '}' at the
1430		# outermost level.
1431		if ($level == 0 && $c eq ';') {
1432			last;
1433		}
1434
1435		# An else is really a conditional as long as its not else if
1436		if ($level == 0 && $coff_set == 0 &&
1437				(!defined($p) || $p =~ /(?:\s|\}|\+)/) &&
1438				$remainder =~ /^(else)(?:\s|{)/ &&
1439				$remainder !~ /^else\s+if\b/) {
1440			$coff = $off + length($1) - 1;
1441			$coff_set = 1;
1442			#warn "CSB: mark coff<$coff> soff<$soff> 1<$1>\n";
1443			#warn "[" . substr($blk, $soff, $coff - $soff + 1) . "]\n";
1444		}
1445
1446		if (($type eq '' || $type eq '(') && $c eq '(') {
1447			$level++;
1448			$type = '(';
1449		}
1450		if ($type eq '(' && $c eq ')') {
1451			$level--;
1452			$type = ($level != 0)? '(' : '';
1453
1454			if ($level == 0 && $coff < $soff) {
1455				$coff = $off;
1456				$coff_set = 1;
1457				#warn "CSB: mark coff<$coff>\n";
1458			}
1459		}
1460		if (($type eq '' || $type eq '{') && $c eq '{') {
1461			$level++;
1462			$type = '{';
1463		}
1464		if ($type eq '{' && $c eq '}') {
1465			$level--;
1466			$type = ($level != 0)? '{' : '';
1467
1468			if ($level == 0) {
1469				if (substr($blk, $off + 1, 1) eq ';') {
1470					$off++;
1471				}
1472				last;
1473			}
1474		}
1475		# Preprocessor commands end at the newline unless escaped.
1476		if ($type eq '#' && $c eq "\n" && $p ne "\\") {
1477			$level--;
1478			$type = '';
1479			$off++;
1480			last;
1481		}
1482		$off++;
1483	}
1484	# We are truly at the end, so shuffle to the next line.
1485	if ($off == $len) {
1486		$loff = $len + 1;
1487		$line++;
1488		$remain--;
1489	}
1490
1491	my $statement = substr($blk, $soff, $off - $soff + 1);
1492	my $condition = substr($blk, $soff, $coff - $soff + 1);
1493
1494	#warn "STATEMENT<$statement>\n";
1495	#warn "CONDITION<$condition>\n";
1496
1497	#print "coff<$coff> soff<$off> loff<$loff>\n";
1498
1499	return ($statement, $condition,
1500			$line, $remain + 1, $off - $loff + 1, $level);
1501}
1502
1503sub statement_lines {
1504	my ($stmt) = @_;
1505
1506	# Strip the diff line prefixes and rip blank lines at start and end.
1507	$stmt =~ s/(^|\n)./$1/g;
1508	$stmt =~ s/^\s*//;
1509	$stmt =~ s/\s*$//;
1510
1511	my @stmt_lines = ($stmt =~ /\n/g);
1512
1513	return $#stmt_lines + 2;
1514}
1515
1516sub statement_rawlines {
1517	my ($stmt) = @_;
1518
1519	my @stmt_lines = ($stmt =~ /\n/g);
1520
1521	return $#stmt_lines + 2;
1522}
1523
1524sub statement_block_size {
1525	my ($stmt) = @_;
1526
1527	$stmt =~ s/(^|\n)./$1/g;
1528	$stmt =~ s/^\s*{//;
1529	$stmt =~ s/}\s*$//;
1530	$stmt =~ s/^\s*//;
1531	$stmt =~ s/\s*$//;
1532
1533	my @stmt_lines = ($stmt =~ /\n/g);
1534	my @stmt_statements = ($stmt =~ /;/g);
1535
1536	my $stmt_lines = $#stmt_lines + 2;
1537	my $stmt_statements = $#stmt_statements + 1;
1538
1539	if ($stmt_lines > $stmt_statements) {
1540		return $stmt_lines;
1541	} else {
1542		return $stmt_statements;
1543	}
1544}
1545
1546sub ctx_statement_full {
1547	my ($linenr, $remain, $off) = @_;
1548	my ($statement, $condition, $level);
1549
1550	my (@chunks);
1551
1552	# Grab the first conditional/block pair.
1553	($statement, $condition, $linenr, $remain, $off, $level) =
1554				ctx_statement_block($linenr, $remain, $off);
1555	#print "F: c<$condition> s<$statement> remain<$remain>\n";
1556	push(@chunks, [ $condition, $statement ]);
1557	if (!($remain > 0 && $condition =~ /^\s*(?:\n[+-])?\s*(?:if|else|do)\b/s)) {
1558		return ($level, $linenr, @chunks);
1559	}
1560
1561	# Pull in the following conditional/block pairs and see if they
1562	# could continue the statement.
1563	for (;;) {
1564		($statement, $condition, $linenr, $remain, $off, $level) =
1565				ctx_statement_block($linenr, $remain, $off);
1566		#print "C: c<$condition> s<$statement> remain<$remain>\n";
1567		last if (!($remain > 0 && $condition =~ /^(?:\s*\n[+-])*\s*(?:else|do)\b/s));
1568		#print "C: push\n";
1569		push(@chunks, [ $condition, $statement ]);
1570	}
1571
1572	return ($level, $linenr, @chunks);
1573}
1574
1575sub ctx_block_get {
1576	my ($linenr, $remain, $outer, $open, $close, $off) = @_;
1577	my $line;
1578	my $start = $linenr - 1;
1579	my $blk = '';
1580	my @o;
1581	my @c;
1582	my @res = ();
1583
1584	my $level = 0;
1585	my @stack = ($level);
1586	for ($line = $start; $remain > 0; $line++) {
1587		next if ($rawlines[$line] =~ /^-/);
1588		$remain--;
1589
1590		$blk .= $rawlines[$line];
1591
1592		# Handle nested #if/#else.
1593		if ($lines[$line] =~ /^.\s*#\s*(?:ifndef|ifdef|if)\s/) {
1594			push(@stack, $level);
1595		} elsif ($lines[$line] =~ /^.\s*#\s*(?:else|elif)\b/) {
1596			$level = $stack[$#stack - 1];
1597		} elsif ($lines[$line] =~ /^.\s*#\s*endif\b/) {
1598			$level = pop(@stack);
1599		}
1600
1601		foreach my $c (split(//, $lines[$line])) {
1602			##print "C<$c>L<$level><$open$close>O<$off>\n";
1603			if ($off > 0) {
1604				$off--;
1605				next;
1606			}
1607
1608			if ($c eq $close && $level > 0) {
1609				$level--;
1610				last if ($level == 0);
1611			} elsif ($c eq $open) {
1612				$level++;
1613			}
1614		}
1615
1616		if (!$outer || $level <= 1) {
1617			push(@res, $rawlines[$line]);
1618		}
1619
1620		last if ($level == 0);
1621	}
1622
1623	return ($level, @res);
1624}
1625sub ctx_block_outer {
1626	my ($linenr, $remain) = @_;
1627
1628	my ($level, @r) = ctx_block_get($linenr, $remain, 1, '{', '}', 0);
1629	return @r;
1630}
1631sub ctx_block {
1632	my ($linenr, $remain) = @_;
1633
1634	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1635	return @r;
1636}
1637sub ctx_statement {
1638	my ($linenr, $remain, $off) = @_;
1639
1640	my ($level, @r) = ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1641	return @r;
1642}
1643sub ctx_block_level {
1644	my ($linenr, $remain) = @_;
1645
1646	return ctx_block_get($linenr, $remain, 0, '{', '}', 0);
1647}
1648sub ctx_statement_level {
1649	my ($linenr, $remain, $off) = @_;
1650
1651	return ctx_block_get($linenr, $remain, 0, '(', ')', $off);
1652}
1653
1654sub ctx_locate_comment {
1655	my ($first_line, $end_line) = @_;
1656
1657	# Catch a comment on the end of the line itself.
1658	my ($current_comment) = ($rawlines[$end_line - 1] =~ m@.*(/\*.*\*/)\s*(?:\\\s*)?$@);
1659	return $current_comment if (defined $current_comment);
1660
1661	# Look through the context and try and figure out if there is a
1662	# comment.
1663	my $in_comment = 0;
1664	$current_comment = '';
1665	for (my $linenr = $first_line; $linenr < $end_line; $linenr++) {
1666		my $line = $rawlines[$linenr - 1];
1667		#warn "           $line\n";
1668		if ($linenr == $first_line and $line =~ m@^.\s*\*@) {
1669			$in_comment = 1;
1670		}
1671		if ($line =~ m@/\*@) {
1672			$in_comment = 1;
1673		}
1674		if (!$in_comment && $current_comment ne '') {
1675			$current_comment = '';
1676		}
1677		$current_comment .= $line . "\n" if ($in_comment);
1678		if ($line =~ m@\*/@) {
1679			$in_comment = 0;
1680		}
1681	}
1682
1683	chomp($current_comment);
1684	return($current_comment);
1685}
1686sub ctx_has_comment {
1687	my ($first_line, $end_line) = @_;
1688	my $cmt = ctx_locate_comment($first_line, $end_line);
1689
1690	##print "LINE: $rawlines[$end_line - 1 ]\n";
1691	##print "CMMT: $cmt\n";
1692
1693	return ($cmt ne '');
1694}
1695
1696sub raw_line {
1697	my ($linenr, $cnt) = @_;
1698
1699	my $offset = $linenr - 1;
1700	$cnt++;
1701
1702	my $line;
1703	while ($cnt) {
1704		$line = $rawlines[$offset++];
1705		next if (defined($line) && $line =~ /^-/);
1706		$cnt--;
1707	}
1708
1709	return $line;
1710}
1711
1712sub get_stat_real {
1713	my ($linenr, $lc) = @_;
1714
1715	my $stat_real = raw_line($linenr, 0);
1716	for (my $count = $linenr + 1; $count <= $lc; $count++) {
1717		$stat_real = $stat_real . "\n" . raw_line($count, 0);
1718	}
1719
1720	return $stat_real;
1721}
1722
1723sub get_stat_here {
1724	my ($linenr, $cnt, $here) = @_;
1725
1726	my $herectx = $here . "\n";
1727	for (my $n = 0; $n < $cnt; $n++) {
1728		$herectx .= raw_line($linenr, $n) . "\n";
1729	}
1730
1731	return $herectx;
1732}
1733
1734sub cat_vet {
1735	my ($vet) = @_;
1736	my ($res, $coded);
1737
1738	$res = '';
1739	while ($vet =~ /([^[:cntrl:]]*)([[:cntrl:]]|$)/g) {
1740		$res .= $1;
1741		if ($2 ne '') {
1742			$coded = sprintf("^%c", unpack('C', $2) + 64);
1743			$res .= $coded;
1744		}
1745	}
1746	$res =~ s/$/\$/;
1747
1748	return $res;
1749}
1750
1751my $av_preprocessor = 0;
1752my $av_pending;
1753my @av_paren_type;
1754my $av_pend_colon;
1755
1756sub annotate_reset {
1757	$av_preprocessor = 0;
1758	$av_pending = '_';
1759	@av_paren_type = ('E');
1760	$av_pend_colon = 'O';
1761}
1762
1763sub annotate_values {
1764	my ($stream, $type) = @_;
1765
1766	my $res;
1767	my $var = '_' x length($stream);
1768	my $cur = $stream;
1769
1770	print "$stream\n" if ($dbg_values > 1);
1771
1772	while (length($cur)) {
1773		@av_paren_type = ('E') if ($#av_paren_type < 0);
1774		print " <" . join('', @av_paren_type) .
1775				"> <$type> <$av_pending>" if ($dbg_values > 1);
1776		if ($cur =~ /^(\s+)/o) {
1777			print "WS($1)\n" if ($dbg_values > 1);
1778			if ($1 =~ /\n/ && $av_preprocessor) {
1779				$type = pop(@av_paren_type);
1780				$av_preprocessor = 0;
1781			}
1782
1783		} elsif ($cur =~ /^(\(\s*$Type\s*)\)/ && $av_pending eq '_') {
1784			print "CAST($1)\n" if ($dbg_values > 1);
1785			push(@av_paren_type, $type);
1786			$type = 'c';
1787
1788		} elsif ($cur =~ /^($Type)\s*(?:$Ident|,|\)|\(|\s*$)/) {
1789			print "DECLARE($1)\n" if ($dbg_values > 1);
1790			$type = 'T';
1791
1792		} elsif ($cur =~ /^($Modifier)\s*/) {
1793			print "MODIFIER($1)\n" if ($dbg_values > 1);
1794			$type = 'T';
1795
1796		} elsif ($cur =~ /^(\#\s*define\s*$Ident)(\(?)/o) {
1797			print "DEFINE($1,$2)\n" if ($dbg_values > 1);
1798			$av_preprocessor = 1;
1799			push(@av_paren_type, $type);
1800			if ($2 ne '') {
1801				$av_pending = 'N';
1802			}
1803			$type = 'E';
1804
1805		} elsif ($cur =~ /^(\#\s*(?:undef\s*$Ident|include\b))/o) {
1806			print "UNDEF($1)\n" if ($dbg_values > 1);
1807			$av_preprocessor = 1;
1808			push(@av_paren_type, $type);
1809
1810		} elsif ($cur =~ /^(\#\s*(?:ifdef|ifndef|if))/o) {
1811			print "PRE_START($1)\n" if ($dbg_values > 1);
1812			$av_preprocessor = 1;
1813
1814			push(@av_paren_type, $type);
1815			push(@av_paren_type, $type);
1816			$type = 'E';
1817
1818		} elsif ($cur =~ /^(\#\s*(?:else|elif))/o) {
1819			print "PRE_RESTART($1)\n" if ($dbg_values > 1);
1820			$av_preprocessor = 1;
1821
1822			push(@av_paren_type, $av_paren_type[$#av_paren_type]);
1823
1824			$type = 'E';
1825
1826		} elsif ($cur =~ /^(\#\s*(?:endif))/o) {
1827			print "PRE_END($1)\n" if ($dbg_values > 1);
1828
1829			$av_preprocessor = 1;
1830
1831			# Assume all arms of the conditional end as this
1832			# one does, and continue as if the #endif was not here.
1833			pop(@av_paren_type);
1834			push(@av_paren_type, $type);
1835			$type = 'E';
1836
1837		} elsif ($cur =~ /^(\\\n)/o) {
1838			print "PRECONT($1)\n" if ($dbg_values > 1);
1839
1840		} elsif ($cur =~ /^(__attribute__)\s*\(?/o) {
1841			print "ATTR($1)\n" if ($dbg_values > 1);
1842			$av_pending = $type;
1843			$type = 'N';
1844
1845		} elsif ($cur =~ /^(sizeof)\s*(\()?/o) {
1846			print "SIZEOF($1)\n" if ($dbg_values > 1);
1847			if (defined $2) {
1848				$av_pending = 'V';
1849			}
1850			$type = 'N';
1851
1852		} elsif ($cur =~ /^(if|while|for)\b/o) {
1853			print "COND($1)\n" if ($dbg_values > 1);
1854			$av_pending = 'E';
1855			$type = 'N';
1856
1857		} elsif ($cur =~/^(case)/o) {
1858			print "CASE($1)\n" if ($dbg_values > 1);
1859			$av_pend_colon = 'C';
1860			$type = 'N';
1861
1862		} elsif ($cur =~/^(return|else|goto|typeof|__typeof__)\b/o) {
1863			print "KEYWORD($1)\n" if ($dbg_values > 1);
1864			$type = 'N';
1865
1866		} elsif ($cur =~ /^(\()/o) {
1867			print "PAREN('$1')\n" if ($dbg_values > 1);
1868			push(@av_paren_type, $av_pending);
1869			$av_pending = '_';
1870			$type = 'N';
1871
1872		} elsif ($cur =~ /^(\))/o) {
1873			my $new_type = pop(@av_paren_type);
1874			if ($new_type ne '_') {
1875				$type = $new_type;
1876				print "PAREN('$1') -> $type\n"
1877							if ($dbg_values > 1);
1878			} else {
1879				print "PAREN('$1')\n" if ($dbg_values > 1);
1880			}
1881
1882		} elsif ($cur =~ /^($Ident)\s*\(/o) {
1883			print "FUNC($1)\n" if ($dbg_values > 1);
1884			$type = 'V';
1885			$av_pending = 'V';
1886
1887		} elsif ($cur =~ /^($Ident\s*):(?:\s*\d+\s*(,|=|;))?/) {
1888			if (defined $2 && $type eq 'C' || $type eq 'T') {
1889				$av_pend_colon = 'B';
1890			} elsif ($type eq 'E') {
1891				$av_pend_colon = 'L';
1892			}
1893			print "IDENT_COLON($1,$type>$av_pend_colon)\n" if ($dbg_values > 1);
1894			$type = 'V';
1895
1896		} elsif ($cur =~ /^($Ident|$Constant)/o) {
1897			print "IDENT($1)\n" if ($dbg_values > 1);
1898			$type = 'V';
1899
1900		} elsif ($cur =~ /^($Assignment)/o) {
1901			print "ASSIGN($1)\n" if ($dbg_values > 1);
1902			$type = 'N';
1903
1904		} elsif ($cur =~/^(;|{|})/) {
1905			print "END($1)\n" if ($dbg_values > 1);
1906			$type = 'E';
1907			$av_pend_colon = 'O';
1908
1909		} elsif ($cur =~/^(,)/) {
1910			print "COMMA($1)\n" if ($dbg_values > 1);
1911			$type = 'C';
1912
1913		} elsif ($cur =~ /^(\?)/o) {
1914			print "QUESTION($1)\n" if ($dbg_values > 1);
1915			$type = 'N';
1916
1917		} elsif ($cur =~ /^(:)/o) {
1918			print "COLON($1,$av_pend_colon)\n" if ($dbg_values > 1);
1919
1920			substr($var, length($res), 1, $av_pend_colon);
1921			if ($av_pend_colon eq 'C' || $av_pend_colon eq 'L') {
1922				$type = 'E';
1923			} else {
1924				$type = 'N';
1925			}
1926			$av_pend_colon = 'O';
1927
1928		} elsif ($cur =~ /^(\[)/o) {
1929			print "CLOSE($1)\n" if ($dbg_values > 1);
1930			$type = 'N';
1931
1932		} elsif ($cur =~ /^(-(?![->])|\+(?!\+)|\*|\&\&|\&)/o) {
1933			my $variant;
1934
1935			print "OPV($1)\n" if ($dbg_values > 1);
1936			if ($type eq 'V') {
1937				$variant = 'B';
1938			} else {
1939				$variant = 'U';
1940			}
1941
1942			substr($var, length($res), 1, $variant);
1943			$type = 'N';
1944
1945		} elsif ($cur =~ /^($Operators)/o) {
1946			print "OP($1)\n" if ($dbg_values > 1);
1947			if ($1 ne '++' && $1 ne '--') {
1948				$type = 'N';
1949			}
1950
1951		} elsif ($cur =~ /(^.)/o) {
1952			print "C($1)\n" if ($dbg_values > 1);
1953		}
1954		if (defined $1) {
1955			$cur = substr($cur, length($1));
1956			$res .= $type x length($1);
1957		}
1958	}
1959
1960	return ($res, $var);
1961}
1962
1963sub possible {
1964	my ($possible, $line) = @_;
1965	my $notPermitted = qr{(?:
1966		^(?:
1967			$Modifier|
1968			$Storage|
1969			$Type|
1970			DEFINE_\S+
1971		)$|
1972		^(?:
1973			goto|
1974			return|
1975			case|
1976			else|
1977			asm|__asm__|
1978			do|
1979			\#|
1980			\#\#|
1981		)(?:\s|$)|
1982		^(?:typedef|struct|enum)\b
1983	    )}x;
1984	warn "CHECK<$possible> ($line)\n" if ($dbg_possible > 2);
1985	if ($possible !~ $notPermitted) {
1986		# Check for modifiers.
1987		$possible =~ s/\s*$Storage\s*//g;
1988		$possible =~ s/\s*$Sparse\s*//g;
1989		if ($possible =~ /^\s*$/) {
1990
1991		} elsif ($possible =~ /\s/) {
1992			$possible =~ s/\s*$Type\s*//g;
1993			for my $modifier (split(' ', $possible)) {
1994				if ($modifier !~ $notPermitted) {
1995					warn "MODIFIER: $modifier ($possible) ($line)\n" if ($dbg_possible);
1996					push(@modifierListFile, $modifier);
1997				}
1998			}
1999
2000		} else {
2001			warn "POSSIBLE: $possible ($line)\n" if ($dbg_possible);
2002			push(@typeListFile, $possible);
2003		}
2004		build_types();
2005	} else {
2006		warn "NOTPOSS: $possible ($line)\n" if ($dbg_possible > 1);
2007	}
2008}
2009
2010my $prefix = '';
2011
2012sub show_type {
2013	my ($type) = @_;
2014
2015	$type =~ tr/[a-z]/[A-Z]/;
2016
2017	return defined $use_type{$type} if (scalar keys %use_type > 0);
2018
2019	return !defined $ignore_type{$type};
2020}
2021
2022sub report {
2023	my ($level, $type, $msg) = @_;
2024
2025	if (!show_type($type) ||
2026	    (defined $tst_only && $msg !~ /\Q$tst_only\E/)) {
2027		return 0;
2028	}
2029	my $output = '';
2030	if ($color) {
2031		if ($level eq 'ERROR') {
2032			$output .= RED;
2033		} elsif ($level eq 'WARNING') {
2034			$output .= YELLOW;
2035		} else {
2036			$output .= GREEN;
2037		}
2038	}
2039	$output .= $prefix . $level . ':';
2040	if ($show_types) {
2041		$output .= BLUE if ($color);
2042		$output .= "$type:";
2043	}
2044	$output .= RESET if ($color);
2045	$output .= ' ' . $msg . "\n";
2046
2047	if ($showfile) {
2048		my @lines = split("\n", $output, -1);
2049		splice(@lines, 1, 1);
2050		$output = join("\n", @lines);
2051	}
2052	$output = (split('\n', $output))[0] . "\n" if ($terse);
2053
2054	push(our @report, $output);
2055
2056	return 1;
2057}
2058
2059sub report_dump {
2060	our @report;
2061}
2062
2063sub fixup_current_range {
2064	my ($lineRef, $offset, $length) = @_;
2065
2066	if ($$lineRef =~ /^\@\@ -\d+,\d+ \+(\d+),(\d+) \@\@/) {
2067		my $o = $1;
2068		my $l = $2;
2069		my $no = $o + $offset;
2070		my $nl = $l + $length;
2071		$$lineRef =~ s/\+$o,$l \@\@/\+$no,$nl \@\@/;
2072	}
2073}
2074
2075sub fix_inserted_deleted_lines {
2076	my ($linesRef, $insertedRef, $deletedRef) = @_;
2077
2078	my $range_last_linenr = 0;
2079	my $delta_offset = 0;
2080
2081	my $old_linenr = 0;
2082	my $new_linenr = 0;
2083
2084	my $next_insert = 0;
2085	my $next_delete = 0;
2086
2087	my @lines = ();
2088
2089	my $inserted = @{$insertedRef}[$next_insert++];
2090	my $deleted = @{$deletedRef}[$next_delete++];
2091
2092	foreach my $old_line (@{$linesRef}) {
2093		my $save_line = 1;
2094		my $line = $old_line;	#don't modify the array
2095		if ($line =~ /^(?:\+\+\+|\-\-\-)\s+\S+/) {	#new filename
2096			$delta_offset = 0;
2097		} elsif ($line =~ /^\@\@ -\d+,\d+ \+\d+,\d+ \@\@/) {	#new hunk
2098			$range_last_linenr = $new_linenr;
2099			fixup_current_range(\$line, $delta_offset, 0);
2100		}
2101
2102		while (defined($deleted) && ${$deleted}{'LINENR'} == $old_linenr) {
2103			$deleted = @{$deletedRef}[$next_delete++];
2104			$save_line = 0;
2105			fixup_current_range(\$lines[$range_last_linenr], $delta_offset--, -1);
2106		}
2107
2108		while (defined($inserted) && ${$inserted}{'LINENR'} == $old_linenr) {
2109			push(@lines, ${$inserted}{'LINE'});
2110			$inserted = @{$insertedRef}[$next_insert++];
2111			$new_linenr++;
2112			fixup_current_range(\$lines[$range_last_linenr], $delta_offset++, 1);
2113		}
2114
2115		if ($save_line) {
2116			push(@lines, $line);
2117			$new_linenr++;
2118		}
2119
2120		$old_linenr++;
2121	}
2122
2123	return @lines;
2124}
2125
2126sub fix_insert_line {
2127	my ($linenr, $line) = @_;
2128
2129	my $inserted = {
2130		LINENR => $linenr,
2131		LINE => $line,
2132	};
2133	push(@fixed_inserted, $inserted);
2134}
2135
2136sub fix_delete_line {
2137	my ($linenr, $line) = @_;
2138
2139	my $deleted = {
2140		LINENR => $linenr,
2141		LINE => $line,
2142	};
2143
2144	push(@fixed_deleted, $deleted);
2145}
2146
2147sub ERROR {
2148	my ($type, $msg) = @_;
2149
2150	if (report("ERROR", $type, $msg)) {
2151		our $clean = 0;
2152		our $cnt_error++;
2153		return 1;
2154	}
2155	return 0;
2156}
2157sub WARN {
2158	my ($type, $msg) = @_;
2159
2160	if (report("WARNING", $type, $msg)) {
2161		our $clean = 0;
2162		our $cnt_warn++;
2163		return 1;
2164	}
2165	return 0;
2166}
2167sub CHK {
2168	my ($type, $msg) = @_;
2169
2170	if ($check && report("CHECK", $type, $msg)) {
2171		our $clean = 0;
2172		our $cnt_chk++;
2173		return 1;
2174	}
2175	return 0;
2176}
2177
2178sub check_absolute_file {
2179	my ($absolute, $herecurr) = @_;
2180	my $file = $absolute;
2181
2182	##print "absolute<$absolute>\n";
2183
2184	# See if any suffix of this path is a path within the tree.
2185	while ($file =~ s@^[^/]*/@@) {
2186		if (-f "$root/$file") {
2187			##print "file<$file>\n";
2188			last;
2189		}
2190	}
2191	if (! -f _)  {
2192		return 0;
2193	}
2194
2195	# It is, so see if the prefix is acceptable.
2196	my $prefix = $absolute;
2197	substr($prefix, -length($file)) = '';
2198
2199	##print "prefix<$prefix>\n";
2200	if ($prefix ne ".../") {
2201		WARN("USE_RELATIVE_PATH",
2202		     "use relative pathname instead of absolute in changelog text\n" . $herecurr);
2203	}
2204}
2205
2206sub trim {
2207	my ($string) = @_;
2208
2209	$string =~ s/^\s+|\s+$//g;
2210
2211	return $string;
2212}
2213
2214sub ltrim {
2215	my ($string) = @_;
2216
2217	$string =~ s/^\s+//;
2218
2219	return $string;
2220}
2221
2222sub rtrim {
2223	my ($string) = @_;
2224
2225	$string =~ s/\s+$//;
2226
2227	return $string;
2228}
2229
2230sub string_find_replace {
2231	my ($string, $find, $replace) = @_;
2232
2233	$string =~ s/$find/$replace/g;
2234
2235	return $string;
2236}
2237
2238sub tabify {
2239	my ($leading) = @_;
2240
2241	my $source_indent = 8;
2242	my $max_spaces_before_tab = $source_indent - 1;
2243	my $spaces_to_tab = " " x $source_indent;
2244
2245	#convert leading spaces to tabs
2246	1 while $leading =~ s@^([\t]*)$spaces_to_tab@$1\t@g;
2247	#Remove spaces before a tab
2248	1 while $leading =~ s@^([\t]*)( {1,$max_spaces_before_tab})\t@$1\t@g;
2249
2250	return "$leading";
2251}
2252
2253sub pos_last_openparen {
2254	my ($line) = @_;
2255
2256	my $pos = 0;
2257
2258	my $opens = $line =~ tr/\(/\(/;
2259	my $closes = $line =~ tr/\)/\)/;
2260
2261	my $last_openparen = 0;
2262
2263	if (($opens == 0) || ($closes >= $opens)) {
2264		return -1;
2265	}
2266
2267	my $len = length($line);
2268
2269	for ($pos = 0; $pos < $len; $pos++) {
2270		my $string = substr($line, $pos);
2271		if ($string =~ /^($FuncArg|$balanced_parens)/) {
2272			$pos += length($1) - 1;
2273		} elsif (substr($line, $pos, 1) eq '(') {
2274			$last_openparen = $pos;
2275		} elsif (index($string, '(') == -1) {
2276			last;
2277		}
2278	}
2279
2280	return length(expand_tabs(substr($line, 0, $last_openparen))) + 1;
2281}
2282
2283sub process {
2284	my $filename = shift;
2285
2286	my $linenr=0;
2287	my $prevline="";
2288	my $prevrawline="";
2289	my $stashline="";
2290	my $stashrawline="";
2291
2292	my $length;
2293	my $indent;
2294	my $previndent=0;
2295	my $stashindent=0;
2296
2297	our $clean = 1;
2298	my $signoff = 0;
2299	my $author = '';
2300	my $authorsignoff = 0;
2301	my $is_patch = 0;
2302	my $is_binding_patch = -1;
2303	my $in_header_lines = $file ? 0 : 1;
2304	my $in_commit_log = 0;		#Scanning lines before patch
2305	my $has_commit_log = 0;		#Encountered lines before patch
2306	my $commit_log_lines = 0;	#Number of commit log lines
2307	my $commit_log_possible_stack_dump = 0;
2308	my $commit_log_long_line = 0;
2309	my $commit_log_has_diff = 0;
2310	my $reported_maintainer_file = 0;
2311	my $reported_abi_update = 0;
2312	my $last_abi_file = '';
2313	my $non_utf8_charset = 0;
2314
2315	my $last_blank_line = 0;
2316	my $last_coalesced_string_linenr = -1;
2317
2318	our @report = ();
2319	our $cnt_lines = 0;
2320	our $cnt_error = 0;
2321	our $cnt_warn = 0;
2322	our $cnt_chk = 0;
2323
2324	# Trace the real file/line as we go.
2325	my $realfile = '';
2326	my $realline = 0;
2327	my $realcnt = 0;
2328	my $here = '';
2329	my $context_function;		#undef'd unless there's a known function
2330	my $in_comment = 0;
2331	my $comment_edge = 0;
2332	my $first_line = 0;
2333	my $p1_prefix = '';
2334
2335	my $prev_values = 'E';
2336
2337	# suppression flags
2338	my %suppress_ifbraces;
2339	my %suppress_whiletrailers;
2340	my %suppress_export;
2341	my $suppress_statement = 0;
2342
2343	my %signatures = ();
2344
2345	# Pre-scan the patch sanitizing the lines.
2346	# Pre-scan the patch looking for any __setup documentation.
2347	#
2348	my @setup_docs = ();
2349	my $setup_docs = 0;
2350
2351	my $camelcase_file_seeded = 0;
2352
2353	my $checklicenseline = 1;
2354
2355	sanitise_line_reset();
2356	my $line;
2357	foreach my $rawline (@rawlines) {
2358		$linenr++;
2359		$line = $rawline;
2360
2361		push(@fixed, $rawline) if ($fix);
2362
2363		if ($rawline=~/^\+\+\+\s+(\S+)/) {
2364			$setup_docs = 0;
2365			if ($1 =~ m@Documentation/admin-guide/kernel-parameters.rst$@) {
2366				$setup_docs = 1;
2367			}
2368			#next;
2369		}
2370		if ($rawline =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@/) {
2371			$realline=$1-1;
2372			if (defined $2) {
2373				$realcnt=$3+1;
2374			} else {
2375				$realcnt=1+1;
2376			}
2377			$in_comment = 0;
2378
2379			# Guestimate if this is a continuing comment.  Run
2380			# the context looking for a comment "edge".  If this
2381			# edge is a close comment then we must be in a comment
2382			# at context start.
2383			my $edge;
2384			my $cnt = $realcnt;
2385			for (my $ln = $linenr + 1; $cnt > 0; $ln++) {
2386				next if (defined $rawlines[$ln - 1] &&
2387					 $rawlines[$ln - 1] =~ /^-/);
2388				$cnt--;
2389				#print "RAW<$rawlines[$ln - 1]>\n";
2390				last if (!defined $rawlines[$ln - 1]);
2391				if ($rawlines[$ln - 1] =~ m@(/\*|\*/)@ &&
2392				    $rawlines[$ln - 1] !~ m@"[^"]*(?:/\*|\*/)[^"]*"@) {
2393					($edge) = $1;
2394					last;
2395				}
2396			}
2397			if (defined $edge && $edge eq '*/') {
2398				$in_comment = 1;
2399			}
2400
2401			# Guestimate if this is a continuing comment.  If this
2402			# is the start of a diff block and this line starts
2403			# ' *' then it is very likely a comment.
2404			if (!defined $edge &&
2405			    $rawlines[$linenr] =~ m@^.\s*(?:\*\*+| \*)(?:\s|$)@)
2406			{
2407				$in_comment = 1;
2408			}
2409
2410			##print "COMMENT:$in_comment edge<$edge> $rawline\n";
2411			sanitise_line_reset($in_comment);
2412
2413		} elsif ($realcnt && $rawline =~ /^(?:\+| |$)/) {
2414			# Standardise the strings and chars within the input to
2415			# simplify matching -- only bother with positive lines.
2416			$line = sanitise_line($rawline);
2417		}
2418
2419		# Check if ABI is being updated.  If so, there's probably no need to
2420		# emit the "does ABI need updating?" message on file add/move/delete
2421		if ($SOF &&
2422		    ($line =~ /\+#define SOF_ABI_MAJOR*/ ||
2423		     $line =~ /\+#define SOF_ABI_MINOR*/ ||
2424		     $line =~ /\+#define SOF_ABI_PATCH*/)) {
2425			$reported_abi_update = 1;
2426		}
2427
2428		push(@lines, $line);
2429
2430		if ($realcnt > 1) {
2431			$realcnt-- if ($line =~ /^(?:\+| |$)/);
2432		} else {
2433			$realcnt = 0;
2434		}
2435
2436		#print "==>$rawline\n";
2437		#print "-->$line\n";
2438
2439		if ($setup_docs && $line =~ /^\+/) {
2440			push(@setup_docs, $line);
2441		}
2442	}
2443
2444	$prefix = '';
2445
2446	$realcnt = 0;
2447	$linenr = 0;
2448	$fixlinenr = -1;
2449	foreach my $line (@lines) {
2450		$linenr++;
2451		$fixlinenr++;
2452		my $sline = $line;	#copy of $line
2453		$sline =~ s/$;/ /g;	#with comments as spaces
2454
2455		my $rawline = $rawlines[$linenr - 1];
2456
2457# check if it's a mode change, rename or start of a patch
2458		if (!$in_commit_log &&
2459		    ($line =~ /^ mode change [0-7]+ => [0-7]+ \S+\s*$/ ||
2460		    ($line =~ /^rename (?:from|to) \S+\s*$/ ||
2461		     $line =~ /^diff --git a\/[\w\/\.\_\-]+ b\/\S+\s*$/))) {
2462			$is_patch = 1;
2463		}
2464
2465#extract the line range in the file after the patch is applied
2466		if (!$in_commit_log &&
2467		    $line =~ /^\@\@ -\d+(?:,\d+)? \+(\d+)(,(\d+))? \@\@(.*)/) {
2468			my $context = $4;
2469			$is_patch = 1;
2470			$first_line = $linenr + 1;
2471			$realline=$1-1;
2472			if (defined $2) {
2473				$realcnt=$3+1;
2474			} else {
2475				$realcnt=1+1;
2476			}
2477			annotate_reset();
2478			$prev_values = 'E';
2479
2480			%suppress_ifbraces = ();
2481			%suppress_whiletrailers = ();
2482			%suppress_export = ();
2483			$suppress_statement = 0;
2484			if ($context =~ /\b(\w+)\s*\(/) {
2485				$context_function = $1;
2486			} else {
2487				undef $context_function;
2488			}
2489			next;
2490
2491# track the line number as we move through the hunk, note that
2492# new versions of GNU diff omit the leading space on completely
2493# blank context lines so we need to count that too.
2494		} elsif ($line =~ /^( |\+|$)/) {
2495			$realline++;
2496			$realcnt-- if ($realcnt != 0);
2497
2498			# Measure the line length and indent.
2499			($length, $indent) = line_stats($rawline);
2500
2501			# Track the previous line.
2502			($prevline, $stashline) = ($stashline, $line);
2503			($previndent, $stashindent) = ($stashindent, $indent);
2504			($prevrawline, $stashrawline) = ($stashrawline, $rawline);
2505
2506			#warn "line<$line>\n";
2507
2508		} elsif ($realcnt == 1) {
2509			$realcnt--;
2510		}
2511
2512		my $hunk_line = ($realcnt != 0);
2513
2514		$here = "#$linenr: " if (!$file);
2515		$here = "#$realline: " if ($file);
2516
2517		my $found_file = 0;
2518		# extract the filename as it passes
2519		if ($line =~ /^diff --git.*?(\S+)$/) {
2520			$realfile = $1;
2521			$realfile =~ s@^([^/]*)/@@ if (!$file);
2522			$in_commit_log = 0;
2523			$found_file = 1;
2524		} elsif ($line =~ /^\+\+\+\s+(\S+)/) {
2525			$realfile = $1;
2526			$realfile =~ s@^([^/]*)/@@ if (!$file);
2527			$in_commit_log = 0;
2528
2529			$p1_prefix = $1;
2530			if (!$file && $tree && $p1_prefix ne '' &&
2531			    -e "$root/$p1_prefix") {
2532				WARN("PATCH_PREFIX",
2533				     "patch prefix '$p1_prefix' exists, appears to be a -p0 patch\n");
2534			}
2535
2536			if ($realfile =~ m@^include/asm/@) {
2537				ERROR("MODIFIED_INCLUDE_ASM",
2538				      "do not modify files in include/asm, change architecture specific files in include/asm-<architecture>\n" . "$here$rawline\n");
2539			}
2540			$found_file = 1;
2541		}
2542
2543#make up the handle for any error we report on this line
2544		if ($showfile) {
2545			$prefix = "$realfile:$realline: "
2546		} elsif ($emacs) {
2547			if ($file) {
2548				$prefix = "$filename:$realline: ";
2549			} else {
2550				$prefix = "$filename:$linenr: ";
2551			}
2552		}
2553
2554		if ($found_file) {
2555			if (is_maintained_obsolete($realfile)) {
2556				WARN("OBSOLETE",
2557				     "$realfile is marked as 'obsolete' in the MAINTAINERS hierarchy.  No unnecessary modifications please.\n");
2558			}
2559			if ($realfile =~ m@^(?:drivers/net/|net/|drivers/staging/)@) {
2560				$check = 1;
2561			} else {
2562				$check = $check_orig;
2563			}
2564			$checklicenseline = 1;
2565
2566			if ($realfile !~ /^MAINTAINERS/) {
2567				my $last_binding_patch = $is_binding_patch;
2568
2569				$is_binding_patch = () = $realfile =~ m@^(?:Documentation/devicetree/|include/dt-bindings/)@;
2570
2571				if (($last_binding_patch != -1) &&
2572				    ($last_binding_patch ^ $is_binding_patch)) {
2573					WARN("DT_SPLIT_BINDING_PATCH",
2574					     "DT binding docs and includes should be a separate patch. See: Documentation/devicetree/bindings/submitting-patches.txt\n");
2575				}
2576			}
2577
2578			next;
2579		}
2580
2581		$here .= "FILE: $realfile:$realline:" if ($realcnt != 0);
2582
2583		my $hereline = "$here\n$rawline\n";
2584		my $herecurr = "$here\n$rawline\n";
2585		my $hereprev = "$here\n$prevrawline\n$rawline\n";
2586
2587		$cnt_lines++ if ($realcnt != 0);
2588
2589# Verify the existence of a commit log if appropriate
2590# 2 is used because a $signature is counted in $commit_log_lines
2591		if ($in_commit_log) {
2592			if ($line !~ /^\s*$/) {
2593				$commit_log_lines++;	#could be a $signature
2594			}
2595		} elsif ($has_commit_log && $commit_log_lines < 2) {
2596			WARN("COMMIT_MESSAGE",
2597			     "Missing commit description - Add an appropriate one\n");
2598			$commit_log_lines = 2;	#warn only once
2599		}
2600
2601# Check if the commit log has what seems like a diff which can confuse patch
2602		if ($in_commit_log && !$commit_log_has_diff &&
2603		    (($line =~ m@^\s+diff\b.*a/[\w/]+@ &&
2604		      $line =~ m@^\s+diff\b.*a/([\w/]+)\s+b/$1\b@) ||
2605		     $line =~ m@^\s*(?:\-\-\-\s+a/|\+\+\+\s+b/)@ ||
2606		     $line =~ m/^\s*\@\@ \-\d+,\d+ \+\d+,\d+ \@\@/)) {
2607			ERROR("DIFF_IN_COMMIT_MSG",
2608			      "Avoid using diff content in the commit message - patch(1) might not work\n" . $herecurr);
2609			$commit_log_has_diff = 1;
2610		}
2611
2612# Check for incorrect file permissions
2613		if ($line =~ /^new (file )?mode.*[7531]\d{0,2}$/) {
2614			my $permhere = $here . "FILE: $realfile\n";
2615			if ($realfile !~ m@scripts/@ &&
2616			    $realfile !~ /\.(py|pl|awk|sh)$/) {
2617				ERROR("EXECUTE_PERMISSIONS",
2618				      "do not set execute permissions for source files\n" . $permhere);
2619			}
2620		}
2621
2622# Check the patch for a From:
2623		if (decode("MIME-Header", $line) =~ /^From:\s*(.*)/) {
2624			$author = $1;
2625			$author = encode("utf8", $author) if ($line =~ /=\?utf-8\?/i);
2626			$author =~ s/"//g;
2627		}
2628
2629# Check the patch for a signoff:
2630		if ($line =~ /^\s*signed-off-by:/i) {
2631			$signoff++;
2632			$in_commit_log = 0;
2633			if ($author ne '') {
2634				my $l = $line;
2635				$l =~ s/"//g;
2636				if ($l =~ /^\s*signed-off-by:\s*\Q$author\E/i) {
2637				    $authorsignoff = 1;
2638				}
2639			}
2640		}
2641
2642
2643# Check if MAINTAINERS is being updated.  If so, there's probably no need to
2644# emit the "does MAINTAINERS need updating?" message on file add/move/delete
2645		if ($line =~ /^\s*MAINTAINERS\s*\|/) {
2646			$reported_maintainer_file = 1;
2647		}
2648
2649# Check signature styles
2650		if (!$in_header_lines &&
2651		    $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
2652			my $space_before = $1;
2653			my $sign_off = $2;
2654			my $space_after = $3;
2655			my $email = $4;
2656			my $ucfirst_sign_off = ucfirst(lc($sign_off));
2657
2658			if ($sign_off !~ /$signature_tags/) {
2659				WARN("BAD_SIGN_OFF",
2660				     "Non-standard signature: $sign_off\n" . $herecurr);
2661			}
2662			if (defined $space_before && $space_before ne "") {
2663				if (WARN("BAD_SIGN_OFF",
2664					 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
2665				    $fix) {
2666					$fixed[$fixlinenr] =
2667					    "$ucfirst_sign_off $email";
2668				}
2669			}
2670			if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
2671				if (WARN("BAD_SIGN_OFF",
2672					 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
2673				    $fix) {
2674					$fixed[$fixlinenr] =
2675					    "$ucfirst_sign_off $email";
2676				}
2677
2678			}
2679			if (!defined $space_after || $space_after ne " ") {
2680				if (WARN("BAD_SIGN_OFF",
2681					 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
2682				    $fix) {
2683					$fixed[$fixlinenr] =
2684					    "$ucfirst_sign_off $email";
2685				}
2686			}
2687
2688			my ($email_name, $email_address, $comment) = parse_email($email);
2689			my $suggested_email = format_email(($email_name, $email_address));
2690			if ($suggested_email eq "") {
2691				ERROR("BAD_SIGN_OFF",
2692				      "Unrecognized email address: '$email'\n" . $herecurr);
2693			} else {
2694				my $dequoted = $suggested_email;
2695				$dequoted =~ s/^"//;
2696				$dequoted =~ s/" </ </;
2697				# Don't force email to have quotes
2698				# Allow just an angle bracketed address
2699				if ("$dequoted$comment" ne $email &&
2700				    "<$email_address>$comment" ne $email &&
2701				    "$suggested_email$comment" ne $email) {
2702					WARN("BAD_SIGN_OFF",
2703					     "email address '$email' might be better as '$suggested_email$comment'\n" . $herecurr);
2704				}
2705			}
2706
2707# Check for duplicate signatures
2708			my $sig_nospace = $line;
2709			$sig_nospace =~ s/\s//g;
2710			$sig_nospace = lc($sig_nospace);
2711			if (defined $signatures{$sig_nospace}) {
2712				WARN("BAD_SIGN_OFF",
2713				     "Duplicate signature\n" . $herecurr);
2714			} else {
2715				$signatures{$sig_nospace} = 1;
2716			}
2717
2718# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
2719			if ($sign_off =~ /^co-developed-by:$/i) {
2720				if ($email eq $author) {
2721					WARN("BAD_SIGN_OFF",
2722					      "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . "$here\n" . $rawline);
2723				}
2724				if (!defined $lines[$linenr]) {
2725					WARN("BAD_SIGN_OFF",
2726                                             "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline);
2727				} elsif ($rawlines[$linenr] !~ /^\s*signed-off-by:\s*(.*)/i) {
2728					WARN("BAD_SIGN_OFF",
2729					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2730				} elsif ($1 ne $email) {
2731					WARN("BAD_SIGN_OFF",
2732					     "Co-developed-by and Signed-off-by: name/email do not match \n" . "$here\n" . $rawline . "\n" .$rawlines[$linenr]);
2733				}
2734			}
2735		}
2736
2737# Check email subject for common tools that don't need to be mentioned
2738		if ($in_header_lines &&
2739		    $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
2740			WARN("EMAIL_SUBJECT",
2741			     "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
2742		}
2743
2744# Check for unwanted Gerrit info
2745		if ($in_commit_log && $line =~ /^\s*change-id:/i) {
2746			ERROR("GERRIT_CHANGE_ID",
2747			      "Remove Gerrit Change-Id's before submitting upstream.\n" . $herecurr);
2748		}
2749
2750# Check if the commit log is in a possible stack dump
2751		if ($in_commit_log && !$commit_log_possible_stack_dump &&
2752		    ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
2753		     $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
2754					# timestamp
2755		     $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
2756		     $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
2757		     $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
2758					# stack dump address styles
2759			$commit_log_possible_stack_dump = 1;
2760		}
2761
2762# Check for line lengths > 75 in commit log, warn once
2763		if ($in_commit_log && !$commit_log_long_line &&
2764		    length($line) > 75 &&
2765		    !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
2766					# file delta changes
2767		      $line =~ /^\s*(?:[\w\.\-]+\/)++[\w\.\-]+:/ ||
2768					# filename then :
2769		      $line =~ /^\s*(?:Fixes:|Link:)/i ||
2770					# A Fixes: or Link: line
2771		      $commit_log_possible_stack_dump)) {
2772			WARN("COMMIT_LOG_LONG_LINE",
2773			     "Possible unwrapped commit description (prefer a maximum 75 chars per line)\n" . $herecurr);
2774			$commit_log_long_line = 1;
2775		}
2776
2777# Reset possible stack dump if a blank line is found
2778		if ($in_commit_log && $commit_log_possible_stack_dump &&
2779		    $line =~ /^\s*$/) {
2780			$commit_log_possible_stack_dump = 0;
2781		}
2782
2783# Check for git id commit length and improperly formed commit descriptions
2784		if ($in_commit_log && !$commit_log_possible_stack_dump &&
2785		    $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink):/i &&
2786		    $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
2787		    ($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
2788		     ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
2789		      $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
2790		      $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
2791			my $init_char = "c";
2792			my $orig_commit = "";
2793			my $short = 1;
2794			my $long = 0;
2795			my $case = 1;
2796			my $space = 1;
2797			my $hasdesc = 0;
2798			my $hasparens = 0;
2799			my $id = '0123456789ab';
2800			my $orig_desc = "commit description";
2801			my $description = "";
2802
2803			if ($line =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
2804				$init_char = $1;
2805				$orig_commit = lc($2);
2806			} elsif ($line =~ /\b([0-9a-f]{12,40})\b/i) {
2807				$orig_commit = lc($1);
2808			}
2809
2810			$short = 0 if ($line =~ /\bcommit\s+[0-9a-f]{12,40}/i);
2811			$long = 1 if ($line =~ /\bcommit\s+[0-9a-f]{41,}/i);
2812			$space = 0 if ($line =~ /\bcommit [0-9a-f]/i);
2813			$case = 0 if ($line =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
2814			if ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)"\)/i) {
2815				$orig_desc = $1;
2816				$hasparens = 1;
2817			} elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s*$/i &&
2818				 defined $rawlines[$linenr] &&
2819				 $rawlines[$linenr] =~ /^\s*\("([^"]+)"\)/) {
2820				$orig_desc = $1;
2821				$hasparens = 1;
2822			} elsif ($line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("[^"]+$/i &&
2823				 defined $rawlines[$linenr] &&
2824				 $rawlines[$linenr] =~ /^\s*[^"]+"\)/) {
2825				$line =~ /\bcommit\s+[0-9a-f]{5,}\s+\("([^"]+)$/i;
2826				$orig_desc = $1;
2827				$rawlines[$linenr] =~ /^\s*([^"]+)"\)/;
2828				$orig_desc .= " " . $1;
2829				$hasparens = 1;
2830			}
2831
2832			($id, $description) = git_commit_info($orig_commit,
2833							      $id, $orig_desc);
2834
2835			if (defined($id) &&
2836			   ($short || $long || $space || $case || ($orig_desc ne $description) || !$hasparens)) {
2837				ERROR("GIT_COMMIT_ID",
2838				      "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herecurr);
2839			}
2840		}
2841
2842# Check for added, moved or deleted files
2843		if (!$SOF &&
2844		    (!$reported_maintainer_file && !$in_commit_log &&
2845		     ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
2846		      $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
2847		      ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
2848		       (defined($1) || defined($2)))))) {
2849			$is_patch = 1;
2850			$reported_maintainer_file = 1;
2851			WARN("FILE_PATH_CHANGES",
2852			     "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
2853		}
2854
2855# Check for wrappage within a valid hunk of the file
2856		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
2857			ERROR("CORRUPTED_PATCH",
2858			      "patch seems to be corrupt (line wrapped?)\n" .
2859				$herecurr) if (!$emitted_corrupt++);
2860		}
2861
2862# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
2863		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
2864		    $rawline !~ m/^$UTF8*$/) {
2865			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
2866
2867			my $blank = copy_spacing($rawline);
2868			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
2869			my $hereptr = "$hereline$ptr\n";
2870
2871			CHK("INVALID_UTF8",
2872			    "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
2873		}
2874
2875# Check if it's the start of a commit log
2876# (not a header line and we haven't seen the patch filename)
2877		if ($in_header_lines && $realfile =~ /^$/ &&
2878		    !($rawline =~ /^\s+(?:\S|$)/ ||
2879		      $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
2880			$in_header_lines = 0;
2881			$in_commit_log = 1;
2882			$has_commit_log = 1;
2883		}
2884
2885# Check if there is UTF-8 in a commit log when a mail header has explicitly
2886# declined it, i.e defined some charset where it is missing.
2887		if ($in_header_lines &&
2888		    $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
2889		    $1 !~ /utf-8/i) {
2890			$non_utf8_charset = 1;
2891		}
2892
2893		if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
2894		    $rawline =~ /$NON_ASCII_UTF8/) {
2895			WARN("UTF8_BEFORE_PATCH",
2896			    "8-bit UTF-8 used in possible commit log\n" . $herecurr);
2897		}
2898
2899# Check for absolute kernel paths in commit message
2900		if ($tree && $in_commit_log) {
2901			while ($line =~ m{(?:^|\s)(/\S*)}g) {
2902				my $file = $1;
2903
2904				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
2905				    check_absolute_file($1, $herecurr)) {
2906					#
2907				} else {
2908					check_absolute_file($file, $herecurr);
2909				}
2910			}
2911		}
2912
2913# Check for various typo / spelling mistakes
2914		if (defined($misspellings) &&
2915		    ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
2916			while ($rawline =~ /(?:^|[^a-z@])($misspellings)(?:\b|$|[^a-z@])/gi) {
2917				my $typo = $1;
2918				my $typo_fix = $spelling_fix{lc($typo)};
2919				$typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
2920				$typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
2921				my $msg_level = \&WARN;
2922				$msg_level = \&CHK if ($file);
2923				if (&{$msg_level}("TYPO_SPELLING",
2924						  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $herecurr) &&
2925				    $fix) {
2926					$fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
2927				}
2928			}
2929		}
2930
2931# check for invalid commit id
2932		if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
2933			my $id;
2934			my $description;
2935			($id, $description) = git_commit_info($2, undef, undef);
2936			if (!defined($id)) {
2937				WARN("UNKNOWN_COMMIT_ID",
2938				     "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
2939			}
2940		}
2941
2942# ignore non-hunk lines and lines being removed
2943		next if (!$hunk_line || $line =~ /^-/);
2944
2945#trailing whitespace
2946		if ($line =~ /^\+.*\015/) {
2947			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2948			if (ERROR("DOS_LINE_ENDINGS",
2949				  "DOS line endings\n" . $herevet) &&
2950			    $fix) {
2951				$fixed[$fixlinenr] =~ s/[\s\015]+$//;
2952			}
2953		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
2954			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2955			if (ERROR("TRAILING_WHITESPACE",
2956				  "trailing whitespace\n" . $herevet) &&
2957			    $fix) {
2958				$fixed[$fixlinenr] =~ s/\s+$//;
2959			}
2960
2961			$rpt_cleaners = 1;
2962		}
2963
2964# Check for FSF mailing addresses.
2965		if ($rawline =~ /\bwrite to the Free/i ||
2966		    $rawline =~ /\b675\s+Mass\s+Ave/i ||
2967		    $rawline =~ /\b59\s+Temple\s+Pl/i ||
2968		    $rawline =~ /\b51\s+Franklin\s+St/i) {
2969			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
2970			my $msg_level = \&ERROR;
2971			$msg_level = \&CHK if ($file);
2972			&{$msg_level}("FSF_MAILING_ADDRESS",
2973				      "Do not include the paragraph about writing to the Free Software Foundation's mailing address from the sample GPL notice. The FSF has changed addresses in the past, and may do so again. Linux already includes a copy of the GPL.\n" . $herevet)
2974		}
2975
2976# check for Kconfig help text having a real description
2977# Only applies when adding the entry originally, after that we do not have
2978# sufficient context to determine whether it is indeed long enough.
2979		if ($realfile =~ /Kconfig/ &&
2980		    # 'choice' is usually the last thing on the line (though
2981		    # Kconfig supports named choices), so use a word boundary
2982		    # (\b) rather than a whitespace character (\s)
2983		    $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
2984			my $length = 0;
2985			my $cnt = $realcnt;
2986			my $ln = $linenr + 1;
2987			my $f;
2988			my $is_start = 0;
2989			my $is_end = 0;
2990			for (; $cnt > 0 && defined $lines[$ln - 1]; $ln++) {
2991				$f = $lines[$ln - 1];
2992				$cnt-- if ($lines[$ln - 1] !~ /^-/);
2993				$is_end = $lines[$ln - 1] =~ /^\+/;
2994
2995				next if ($f =~ /^-/);
2996				last if (!$file && $f =~ /^\@\@/);
2997
2998				if ($lines[$ln - 1] =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
2999					$is_start = 1;
3000				} elsif ($lines[$ln - 1] =~ /^\+\s*(?:help|---help---)\s*$/) {
3001					if ($lines[$ln - 1] =~ "---help---") {
3002						WARN("CONFIG_DESCRIPTION",
3003						     "prefer 'help' over '---help---' for new help texts\n" . $herecurr);
3004					}
3005					$length = -1;
3006				}
3007
3008				$f =~ s/^.//;
3009				$f =~ s/#.*//;
3010				$f =~ s/^\s+//;
3011				next if ($f =~ /^$/);
3012
3013				# This only checks context lines in the patch
3014				# and so hopefully shouldn't trigger false
3015				# positives, even though some of these are
3016				# common words in help texts
3017				if ($f =~ /^\s*(?:config|menuconfig|choice|endchoice|
3018						  if|endif|menu|endmenu|source)\b/x) {
3019					$is_end = 1;
3020					last;
3021				}
3022				$length++;
3023			}
3024			if ($is_start && $is_end && $length < $min_conf_desc_length) {
3025				WARN("CONFIG_DESCRIPTION",
3026				     "please write a paragraph that describes the config symbol fully\n" . $herecurr);
3027			}
3028			#print "is_start<$is_start> is_end<$is_end> length<$length>\n";
3029		}
3030
3031# check for MAINTAINERS entries that don't have the right form
3032		if ($realfile =~ /^MAINTAINERS$/ &&
3033		    $rawline =~ /^\+[A-Z]:/ &&
3034		    $rawline !~ /^\+[A-Z]:\t\S/) {
3035			if (WARN("MAINTAINERS_STYLE",
3036				 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3037			    $fix) {
3038				$fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3039			}
3040		}
3041
3042# discourage the use of boolean for type definition attributes of Kconfig options
3043		if ($realfile =~ /Kconfig/ &&
3044		    $line =~ /^\+\s*\bboolean\b/) {
3045			WARN("CONFIG_TYPE_BOOLEAN",
3046			     "Use of boolean is deprecated, please use bool instead.\n" . $herecurr);
3047		}
3048
3049		if (($realfile =~ /Makefile.*/ || $realfile =~ /Kbuild.*/) &&
3050		    ($line =~ /\+(EXTRA_[A-Z]+FLAGS).*/)) {
3051			my $flag = $1;
3052			my $replacement = {
3053				'EXTRA_AFLAGS' =>   'asflags-y',
3054				'EXTRA_CFLAGS' =>   'ccflags-y',
3055				'EXTRA_CPPFLAGS' => 'cppflags-y',
3056				'EXTRA_LDFLAGS' =>  'ldflags-y',
3057			};
3058
3059			WARN("DEPRECATED_VARIABLE",
3060			     "Use of $flag is deprecated, please use \`$replacement->{$flag} instead.\n" . $herecurr) if ($replacement->{$flag});
3061		}
3062
3063# check for DT compatible documentation
3064		if (defined $root &&
3065			(($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3066			 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3067
3068			my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3069
3070			my $dt_path = $root . "/Documentation/devicetree/bindings/";
3071			my $vp_file = $dt_path . "vendor-prefixes.yaml";
3072
3073			foreach my $compat (@compats) {
3074				my $compat2 = $compat;
3075				$compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3076				my $compat3 = $compat;
3077				$compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3078				`grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3079				if ( $? >> 8 ) {
3080					WARN("UNDOCUMENTED_DT_STRING",
3081					     "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3082				}
3083
3084				next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3085				my $vendor = $1;
3086				`grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3087				if ( $? >> 8 ) {
3088					WARN("UNDOCUMENTED_DT_STRING",
3089					     "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3090				}
3091			}
3092		}
3093
3094# check for using SPDX license tag at beginning of files
3095		if ($realline == $checklicenseline) {
3096			if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3097				$checklicenseline = 2;
3098			} elsif ($rawline =~ /^\+/) {
3099				my $comment = "";
3100				if ($realfile =~ /\.(h|s|S)$/) {
3101					$comment = '/*';
3102				} elsif ($realfile =~ /\.(c|dts|dtsi)$/) {
3103					$comment = '//';
3104				} elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc)$/) {
3105					$comment = '#';
3106				} elsif ($realfile =~ /\.rst$/) {
3107					$comment = '..';
3108				}
3109
3110# check SPDX comment style for .[chsS] files
3111				if ($realfile =~ /\.[chsS]$/ &&
3112				    $rawline =~ /SPDX-License-Identifier:/ &&
3113				    $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3114					WARN("SPDX_LICENSE_TAG",
3115					     "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3116				}
3117
3118				if ($comment !~ /^$/ &&
3119				    $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3120					WARN("SPDX_LICENSE_TAG",
3121					     "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3122				} elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3123					my $spdx_license = $1;
3124					if (!is_SPDX_License_valid($spdx_license)) {
3125						WARN("SPDX_LICENSE_TAG",
3126						     "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3127					}
3128				}
3129			}
3130		}
3131
3132# check we are in a valid source file if not then ignore this hunk
3133		next if ($realfile !~ /\.(h|c|s|S|sh|dtsi|dts)$/);
3134
3135# check for using SPDX-License-Identifier on the wrong line number
3136		if ($realline != $checklicenseline &&
3137		    $rawline =~ /\bSPDX-License-Identifier:/ &&
3138		    substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3139			WARN("SPDX_LICENSE_TAG",
3140			     "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3141		}
3142
3143# line length limit (with some exclusions)
3144#
3145# There are a few types of lines that may extend beyond $max_line_length:
3146#	logging functions like pr_info that end in a string
3147#	lines with a single string
3148#	#defines that are a single string
3149#	lines with an RFC3986 like URL
3150#
3151# There are 3 different line length message types:
3152# LONG_LINE_COMMENT	a comment starts before but extends beyond $max_line_length
3153# LONG_LINE_STRING	a string starts before but extends beyond $max_line_length
3154# LONG_LINE		all other lines longer than $max_line_length
3155#
3156# if LONG_LINE is ignored, the other 2 types are also ignored
3157#
3158
3159		if ($line =~ /^\+/ && $length > $max_line_length) {
3160			my $msg_type = "LONG_LINE";
3161
3162			# Check the allowed long line types first
3163
3164			# logging functions that end in a string that starts
3165			# before $max_line_length
3166			if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3167			    length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3168				$msg_type = "";
3169
3170			# lines with only strings (w/ possible termination)
3171			# #defines with only strings
3172			} elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3173				 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3174				$msg_type = "";
3175
3176			# More special cases
3177			} elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3178				 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3179				$msg_type = "";
3180
3181			# URL ($rawline is used in case the URL is in a comment)
3182			} elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3183				$msg_type = "";
3184
3185			# Otherwise set the alternate message types
3186
3187			# a comment starts before $max_line_length
3188			} elsif ($line =~ /($;[\s$;]*)$/ &&
3189				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3190				$msg_type = "LONG_LINE_COMMENT"
3191
3192			# a quoted string starts before $max_line_length
3193			} elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3194				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3195				$msg_type = "LONG_LINE_STRING"
3196			}
3197
3198			if ($msg_type ne "" &&
3199			    (show_type("LONG_LINE") || show_type($msg_type))) {
3200				my $msg_level = \&WARN;
3201				$msg_level = \&CHK if ($file);
3202				&{$msg_level}($msg_type,
3203					      "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3204			}
3205		}
3206
3207# check for adding lines without a newline.
3208		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3209			WARN("MISSING_EOF_NEWLINE",
3210			     "adding a line without newline at end of file\n" . $herecurr);
3211		}
3212
3213# check we are in a valid source file C or perl if not then ignore this hunk
3214		next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3215
3216# at the beginning of a line any tabs must come first and anything
3217# more than 8 must use tabs.
3218		if ($rawline =~ /^\+\s* \t\s*\S/ ||
3219		    $rawline =~ /^\+\s*        \s*/) {
3220			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3221			$rpt_cleaners = 1;
3222			if (ERROR("CODE_INDENT",
3223				  "code indent should use tabs where possible\n" . $herevet) &&
3224			    $fix) {
3225				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3226			}
3227		}
3228
3229# check for space before tabs.
3230		if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3231			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3232			if (WARN("SPACE_BEFORE_TAB",
3233				"please, no space before tabs\n" . $herevet) &&
3234			    $fix) {
3235				while ($fixed[$fixlinenr] =~
3236					   s/(^\+.*) {8,8}\t/$1\t\t/) {}
3237				while ($fixed[$fixlinenr] =~
3238					   s/(^\+.*) +\t/$1\t/) {}
3239			}
3240		}
3241
3242# check for assignments on the start of a line
3243		if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3244			CHK("ASSIGNMENT_CONTINUATIONS",
3245			    "Assignment operator '$1' should be on the previous line\n" . $hereprev);
3246		}
3247
3248# check for && or || at the start of a line
3249		if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3250			CHK("LOGICAL_CONTINUATIONS",
3251			    "Logical continuations should be on the previous line\n" . $hereprev);
3252		}
3253
3254# check indentation starts on a tab stop
3255		if ($perl_version_ok &&
3256		    $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3257			my $indent = length($1);
3258			if ($indent % 8) {
3259				if (WARN("TABSTOP",
3260					 "Statements should start on a tabstop\n" . $herecurr) &&
3261				    $fix) {
3262					$fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/8)@e;
3263				}
3264			}
3265		}
3266
3267# check multi-line statement indentation matches previous line
3268		if ($perl_version_ok &&
3269		    $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3270			$prevline =~ /^\+(\t*)(.*)$/;
3271			my $oldindent = $1;
3272			my $rest = $2;
3273
3274			my $pos = pos_last_openparen($rest);
3275			if ($pos >= 0) {
3276				$line =~ /^(\+| )([ \t]*)/;
3277				my $newindent = $2;
3278
3279				my $goodtabindent = $oldindent .
3280					"\t" x ($pos / 8) .
3281					" "  x ($pos % 8);
3282				my $goodspaceindent = $oldindent . " "  x $pos;
3283
3284				if ($newindent ne $goodtabindent &&
3285				    $newindent ne $goodspaceindent) {
3286
3287					if (CHK("PARENTHESIS_ALIGNMENT",
3288						"Alignment should match open parenthesis\n" . $hereprev) &&
3289					    $fix && $line =~ /^\+/) {
3290						$fixed[$fixlinenr] =~
3291						    s/^\+[ \t]*/\+$goodtabindent/;
3292					}
3293				}
3294			}
3295		}
3296
3297# check for space after cast like "(int) foo" or "(struct foo) bar"
3298# avoid checking a few false positives:
3299#   "sizeof(<type>)" or "__alignof__(<type>)"
3300#   function pointer declarations like "(*foo)(int) = bar;"
3301#   structure definitions like "(struct foo) { 0 };"
3302#   multiline macros that define functions
3303#   known attributes or the __attribute__ keyword
3304		if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
3305		    (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
3306			if (CHK("SPACING",
3307				"No space is necessary after a cast\n" . $herecurr) &&
3308			    $fix) {
3309				$fixed[$fixlinenr] =~
3310				    s/(\(\s*$Type\s*\))[ \t]+/$1/;
3311			}
3312		}
3313
3314# Block comment styles
3315# Networking with an initial /*
3316		if ($realfile =~ m@^(drivers/net/|net/)@ &&
3317		    $prevrawline =~ /^\+[ \t]*\/\*[ \t]*$/ &&
3318		    $rawline =~ /^\+[ \t]*\*/ &&
3319		    $realline > 2) {
3320			WARN("NETWORKING_BLOCK_COMMENT_STYLE",
3321			     "networking block comments don't use an empty /* line, use /* Comment...\n" . $hereprev);
3322		}
3323
3324# UAPI ABI version
3325		if ($SOF && $realfile ne $last_abi_file &&
3326		    $realfile =~ m@^(src/include/ipc/|src/include/kernel/|src/include/user/)@ &&
3327		    $rawline =~ /^\+/ &&
3328		    !$reported_abi_update) {
3329			$last_abi_file = $realfile;
3330			WARN("ABI update ??",
3331			     "Please update ABI in accordance with http://semver.org\n" . $hereprev);
3332		}
3333
3334# Block comments use * on subsequent lines
3335		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
3336		    $prevrawline =~ /^\+.*?\/\*/ &&		#starting /*
3337		    $prevrawline !~ /\*\/[ \t]*$/ &&		#no trailing */
3338		    $rawline =~ /^\+/ &&			#line is new
3339		    $rawline !~ /^\+[ \t]*\*/) {		#no leading *
3340			WARN("BLOCK_COMMENT_STYLE",
3341			     "Block comments use * on subsequent lines\n" . $hereprev);
3342		}
3343
3344# Block comments use */ on trailing lines
3345		if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&	#trailing */
3346		    $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&	#inline /*...*/
3347		    $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&	#trailing **/
3348		    $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {	#non blank */
3349			WARN("BLOCK_COMMENT_STYLE",
3350			     "Block comments use a trailing */ on a separate line\n" . $herecurr);
3351		}
3352
3353# Block comment * alignment
3354		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
3355		    $line =~ /^\+[ \t]*$;/ &&			#leading comment
3356		    $rawline =~ /^\+[ \t]*\*/ &&		#leading *
3357		    (($prevrawline =~ /^\+.*?\/\*/ &&		#leading /*
3358		      $prevrawline !~ /\*\/[ \t]*$/) ||		#no trailing */
3359		     $prevrawline =~ /^\+[ \t]*\*/)) {		#leading *
3360			my $oldindent;
3361			$prevrawline =~ m@^\+([ \t]*/?)\*@;
3362			if (defined($1)) {
3363				$oldindent = expand_tabs($1);
3364			} else {
3365				$prevrawline =~ m@^\+(.*/?)\*@;
3366				$oldindent = expand_tabs($1);
3367			}
3368			$rawline =~ m@^\+([ \t]*)\*@;
3369			my $newindent = $1;
3370			$newindent = expand_tabs($newindent);
3371			if (length($oldindent) ne length($newindent)) {
3372				WARN("BLOCK_COMMENT_STYLE",
3373				     "Block comments should align the * on each line\n" . $hereprev);
3374			}
3375		}
3376
3377# check for missing blank lines after struct/union declarations
3378# with exceptions for various attributes and macros
3379		if ($prevline =~ /^[\+ ]};?\s*$/ &&
3380		    $line =~ /^\+/ &&
3381		    !($line =~ /^\+\s*$/ ||
3382		      $line =~ /^\+\s*EXPORT_SYMBOL/ ||
3383		      $line =~ /^\+\s*MODULE_/i ||
3384		      $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
3385		      $line =~ /^\+[a-z_]*init/ ||
3386		      $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
3387		      $line =~ /^\+\s*DECLARE/ ||
3388		      $line =~ /^\+\s*builtin_[\w_]*driver/ ||
3389		      $line =~ /^\+\s*__setup/)) {
3390			if (CHK("LINE_SPACING",
3391				"Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
3392			    $fix) {
3393				fix_insert_line($fixlinenr, "\+");
3394			}
3395		}
3396
3397# check for multiple consecutive blank lines
3398		if ($prevline =~ /^[\+ ]\s*$/ &&
3399		    $line =~ /^\+\s*$/ &&
3400		    $last_blank_line != ($linenr - 1)) {
3401			if (CHK("LINE_SPACING",
3402				"Please don't use multiple blank lines\n" . $hereprev) &&
3403			    $fix) {
3404				fix_delete_line($fixlinenr, $rawline);
3405			}
3406
3407			$last_blank_line = $linenr;
3408		}
3409
3410# check for missing blank lines after declarations
3411		if ($sline =~ /^\+\s+\S/ &&			#Not at char 1
3412			# actual declarations
3413		    ($prevline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3414			# function pointer declarations
3415		     $prevline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3416			# foo bar; where foo is some local typedef or #define
3417		     $prevline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3418			# known declaration macros
3419		     $prevline =~ /^\+\s+$declaration_macros/) &&
3420			# for "else if" which can look like "$Ident $Ident"
3421		    !($prevline =~ /^\+\s+$c90_Keywords\b/ ||
3422			# other possible extensions of declaration lines
3423		      $prevline =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
3424			# not starting a section or a macro "\" extended line
3425		      $prevline =~ /(?:\{\s*|\\)$/) &&
3426			# looks like a declaration
3427		    !($sline =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
3428			# function pointer declarations
3429		      $sline =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
3430			# foo bar; where foo is some local typedef or #define
3431		      $sline =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
3432			# known declaration macros
3433		      $sline =~ /^\+\s+$declaration_macros/ ||
3434			# start of struct or union or enum
3435		      $sline =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
3436			# start or end of block or continuation of declaration
3437		      $sline =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
3438			# bitfield continuation
3439		      $sline =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
3440			# other possible extensions of declaration lines
3441		      $sline =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/) &&
3442			# indentation of previous and current line are the same
3443		    (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/)) {
3444			if (WARN("LINE_SPACING",
3445				 "Missing a blank line after declarations\n" . $hereprev) &&
3446			    $fix) {
3447				fix_insert_line($fixlinenr, "\+");
3448			}
3449		}
3450
3451# check for spaces at the beginning of a line.
3452# Exceptions:
3453#  1) within comments
3454#  2) indented preprocessor commands
3455#  3) hanging labels
3456		if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
3457			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3458			if (WARN("LEADING_SPACE",
3459				 "please, no spaces at the start of a line\n" . $herevet) &&
3460			    $fix) {
3461				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3462			}
3463		}
3464
3465# check we are in a valid C source file if not then ignore this hunk
3466		next if ($realfile !~ /\.(h|c)$/);
3467
3468# check for unusual line ending [ or (
3469		if ($line =~ /^\+.*([\[\(])\s*$/) {
3470			CHK("OPEN_ENDED_LINE",
3471			    "Lines should not end with a '$1'\n" . $herecurr);
3472		}
3473
3474# check if this appears to be the start function declaration, save the name
3475		if ($sline =~ /^\+\{\s*$/ &&
3476		    $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
3477			$context_function = $1;
3478		}
3479
3480# check if this appears to be the end of function declaration
3481		if ($sline =~ /^\+\}\s*$/) {
3482			undef $context_function;
3483		}
3484
3485# check indentation of any line with a bare else
3486# (but not if it is a multiple line "if (foo) return bar; else return baz;")
3487# if the previous line is a break or return and is indented 1 tab more...
3488		if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
3489			my $tabs = length($1) + 1;
3490			if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
3491			    ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
3492			     defined $lines[$linenr] &&
3493			     $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
3494				WARN("UNNECESSARY_ELSE",
3495				     "else is not generally useful after a break or return\n" . $hereprev);
3496			}
3497		}
3498
3499# check indentation of a line with a break;
3500# if the previous line is a goto or return and is indented the same # of tabs
3501		if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
3502			my $tabs = $1;
3503			if ($prevline =~ /^\+$tabs(?:goto|return)\b/) {
3504				WARN("UNNECESSARY_BREAK",
3505				     "break is not useful after a goto or return\n" . $hereprev);
3506			}
3507		}
3508
3509# check for RCS/CVS revision markers
3510		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
3511			WARN("CVS_KEYWORD",
3512			     "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
3513		}
3514
3515# check for old HOTPLUG __dev<foo> section markings
3516		if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
3517			WARN("HOTPLUG_SECTION",
3518			     "Using $1 is unnecessary\n" . $herecurr);
3519		}
3520
3521# Check for potential 'bare' types
3522		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
3523		    $realline_next);
3524#print "LINE<$line>\n";
3525		if ($linenr > $suppress_statement &&
3526		    $realcnt && $sline =~ /.\s*\S/) {
3527			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3528				ctx_statement_block($linenr, $realcnt, 0);
3529			$stat =~ s/\n./\n /g;
3530			$cond =~ s/\n./\n /g;
3531
3532#print "linenr<$linenr> <$stat>\n";
3533			# If this statement has no statement boundaries within
3534			# it there is no point in retrying a statement scan
3535			# until we hit end of it.
3536			my $frag = $stat; $frag =~ s/;+\s*$//;
3537			if ($frag !~ /(?:{|;)/) {
3538#print "skip<$line_nr_next>\n";
3539				$suppress_statement = $line_nr_next;
3540			}
3541
3542			# Find the real next line.
3543			$realline_next = $line_nr_next;
3544			if (defined $realline_next &&
3545			    (!defined $lines[$realline_next - 1] ||
3546			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
3547				$realline_next++;
3548			}
3549
3550			my $s = $stat;
3551			$s =~ s/{.*$//s;
3552
3553			# Ignore goto labels.
3554			if ($s =~ /$Ident:\*$/s) {
3555
3556			# Ignore functions being called
3557			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
3558
3559			} elsif ($s =~ /^.\s*else\b/s) {
3560
3561			# declarations always start with types
3562			} elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) {
3563				my $type = $1;
3564				$type =~ s/\s+/ /g;
3565				possible($type, "A:" . $s);
3566
3567			# definitions in global scope can only start with types
3568			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
3569				possible($1, "B:" . $s);
3570			}
3571
3572			# any (foo ... *) is a pointer cast, and foo is a type
3573			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
3574				possible($1, "C:" . $s);
3575			}
3576
3577			# Check for any sort of function declaration.
3578			# int foo(something bar, other baz);
3579			# void (*store_gdt)(x86_descr_ptr *);
3580			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
3581				my ($name_len) = length($1);
3582
3583				my $ctx = $s;
3584				substr($ctx, 0, $name_len + 1, '');
3585				$ctx =~ s/\)[^\)]*$//;
3586
3587				for my $arg (split(/\s*,\s*/, $ctx)) {
3588					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
3589
3590						possible($1, "D:" . $s);
3591					}
3592				}
3593			}
3594
3595		}
3596
3597#
3598# Checks which may be anchored in the context.
3599#
3600
3601# Check for switch () and associated case and default
3602# statements should be at the same indent.
3603		if ($line=~/\bswitch\s*\(.*\)/) {
3604			my $err = '';
3605			my $sep = '';
3606			my @ctx = ctx_block_outer($linenr, $realcnt);
3607			shift(@ctx);
3608			for my $ctx (@ctx) {
3609				my ($clen, $cindent) = line_stats($ctx);
3610				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
3611							$indent != $cindent) {
3612					$err .= "$sep$ctx\n";
3613					$sep = '';
3614				} else {
3615					$sep = "[...]\n";
3616				}
3617			}
3618			if ($err ne '') {
3619				ERROR("SWITCH_CASE_INDENT_LEVEL",
3620				      "switch and case should be at the same indent\n$hereline$err");
3621			}
3622		}
3623
3624# if/while/etc brace do not go on next line, unless defining a do while loop,
3625# or if that brace on the next line is for something else
3626		if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
3627			my $pre_ctx = "$1$2";
3628
3629			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
3630
3631			if ($line =~ /^\+\t{6,}/) {
3632				WARN("DEEP_INDENTATION",
3633				     "Too many leading tabs - consider code refactoring\n" . $herecurr);
3634			}
3635
3636			my $ctx_cnt = $realcnt - $#ctx - 1;
3637			my $ctx = join("\n", @ctx);
3638
3639			my $ctx_ln = $linenr;
3640			my $ctx_skip = $realcnt;
3641
3642			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
3643					defined $lines[$ctx_ln - 1] &&
3644					$lines[$ctx_ln - 1] =~ /^-/)) {
3645				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
3646				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
3647				$ctx_ln++;
3648			}
3649
3650			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
3651			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
3652
3653			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
3654				ERROR("OPEN_BRACE",
3655				      "that open brace { should be on the previous line\n" .
3656					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3657			}
3658			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
3659			    $ctx =~ /\)\s*\;\s*$/ &&
3660			    defined $lines[$ctx_ln - 1])
3661			{
3662				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
3663				if ($nindent > $indent) {
3664					WARN("TRAILING_SEMICOLON",
3665					     "trailing semicolon indicates no statements, indent implies otherwise\n" .
3666						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
3667				}
3668			}
3669		}
3670
3671# Check relative indent for conditionals and blocks.
3672		if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
3673			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
3674				ctx_statement_block($linenr, $realcnt, 0)
3675					if (!defined $stat);
3676			my ($s, $c) = ($stat, $cond);
3677
3678			substr($s, 0, length($c), '');
3679
3680			# remove inline comments
3681			$s =~ s/$;/ /g;
3682			$c =~ s/$;/ /g;
3683
3684			# Find out how long the conditional actually is.
3685			my @newlines = ($c =~ /\n/gs);
3686			my $cond_lines = 1 + $#newlines;
3687
3688			# Make sure we remove the line prefixes as we have
3689			# none on the first line, and are going to readd them
3690			# where necessary.
3691			$s =~ s/\n./\n/gs;
3692			while ($s =~ /\n\s+\\\n/) {
3693				$cond_lines += $s =~ s/\n\s+\\\n/\n/g;
3694			}
3695
3696			# We want to check the first line inside the block
3697			# starting at the end of the conditional, so remove:
3698			#  1) any blank line termination
3699			#  2) any opening brace { on end of the line
3700			#  3) any do (...) {
3701			my $continuation = 0;
3702			my $check = 0;
3703			$s =~ s/^.*\bdo\b//;
3704			$s =~ s/^\s*{//;
3705			if ($s =~ s/^\s*\\//) {
3706				$continuation = 1;
3707			}
3708			if ($s =~ s/^\s*?\n//) {
3709				$check = 1;
3710				$cond_lines++;
3711			}
3712
3713			# Also ignore a loop construct at the end of a
3714			# preprocessor statement.
3715			if (($prevline =~ /^.\s*#\s*define\s/ ||
3716			    $prevline =~ /\\\s*$/) && $continuation == 0) {
3717				$check = 0;
3718			}
3719
3720			my $cond_ptr = -1;
3721			$continuation = 0;
3722			while ($cond_ptr != $cond_lines) {
3723				$cond_ptr = $cond_lines;
3724
3725				# If we see an #else/#elif then the code
3726				# is not linear.
3727				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
3728					$check = 0;
3729				}
3730
3731				# Ignore:
3732				#  1) blank lines, they should be at 0,
3733				#  2) preprocessor lines, and
3734				#  3) labels.
3735				if ($continuation ||
3736				    $s =~ /^\s*?\n/ ||
3737				    $s =~ /^\s*#\s*?/ ||
3738				    $s =~ /^\s*$Ident\s*:/) {
3739					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
3740					if ($s =~ s/^.*?\n//) {
3741						$cond_lines++;
3742					}
3743				}
3744			}
3745
3746			my (undef, $sindent) = line_stats("+" . $s);
3747			my $stat_real = raw_line($linenr, $cond_lines);
3748
3749			# Check if either of these lines are modified, else
3750			# this is not this patch's fault.
3751			if (!defined($stat_real) ||
3752			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
3753				$check = 0;
3754			}
3755			if (defined($stat_real) && $cond_lines > 1) {
3756				$stat_real = "[...]\n$stat_real";
3757			}
3758
3759			#print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n";
3760
3761			if ($check && $s ne '' &&
3762			    (($sindent % 8) != 0 ||
3763			     ($sindent < $indent) ||
3764			     ($sindent == $indent &&
3765			      ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
3766			     ($sindent > $indent + 8))) {
3767				WARN("SUSPECT_CODE_INDENT",
3768				     "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
3769			}
3770		}
3771
3772		# Track the 'values' across context and added lines.
3773		my $opline = $line; $opline =~ s/^./ /;
3774		my ($curr_values, $curr_vars) =
3775				annotate_values($opline . "\n", $prev_values);
3776		$curr_values = $prev_values . $curr_values;
3777		if ($dbg_values) {
3778			my $outline = $opline; $outline =~ s/\t/ /g;
3779			print "$linenr > .$outline\n";
3780			print "$linenr > $curr_values\n";
3781			print "$linenr >  $curr_vars\n";
3782		}
3783		$prev_values = substr($curr_values, -1);
3784
3785#ignore lines not being added
3786		next if ($line =~ /^[^\+]/);
3787
3788# check for dereferences that span multiple lines
3789		if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
3790		    $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
3791			$prevline =~ /($Lval\s*(?:\.|->))\s*$/;
3792			my $ref = $1;
3793			$line =~ /^.\s*($Lval)/;
3794			$ref .= $1;
3795			$ref =~ s/\s//g;
3796			WARN("MULTILINE_DEREFERENCE",
3797			     "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
3798		}
3799
3800# check for declarations of signed or unsigned without int
3801		while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
3802			my $type = $1;
3803			my $var = $2;
3804			$var = "" if (!defined $var);
3805			if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
3806				my $sign = $1;
3807				my $pointer = $2;
3808
3809				$pointer = "" if (!defined $pointer);
3810
3811				if (WARN("UNSPECIFIED_INT",
3812					 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
3813				    $fix) {
3814					my $decl = trim($sign) . " int ";
3815					my $comp_pointer = $pointer;
3816					$comp_pointer =~ s/\s//g;
3817					$decl .= $comp_pointer;
3818					$decl = rtrim($decl) if ($var eq "");
3819					$fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
3820				}
3821			}
3822		}
3823
3824# TEST: allow direct testing of the type matcher.
3825		if ($dbg_type) {
3826			if ($line =~ /^.\s*$Declare\s*$/) {
3827				ERROR("TEST_TYPE",
3828				      "TEST: is type\n" . $herecurr);
3829			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
3830				ERROR("TEST_NOT_TYPE",
3831				      "TEST: is not type ($1 is)\n". $herecurr);
3832			}
3833			next;
3834		}
3835# TEST: allow direct testing of the attribute matcher.
3836		if ($dbg_attr) {
3837			if ($line =~ /^.\s*$Modifier\s*$/) {
3838				ERROR("TEST_ATTR",
3839				      "TEST: is attr\n" . $herecurr);
3840			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
3841				ERROR("TEST_NOT_ATTR",
3842				      "TEST: is not attr ($1 is)\n". $herecurr);
3843			}
3844			next;
3845		}
3846
3847# check for initialisation to aggregates open brace on the next line
3848		if ($line =~ /^.\s*{/ &&
3849		    $prevline =~ /(?:^|[^=])=\s*$/) {
3850			if (ERROR("OPEN_BRACE",
3851				  "that open brace { should be on the previous line\n" . $hereprev) &&
3852			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
3853				fix_delete_line($fixlinenr - 1, $prevrawline);
3854				fix_delete_line($fixlinenr, $rawline);
3855				my $fixedline = $prevrawline;
3856				$fixedline =~ s/\s*=\s*$/ = {/;
3857				fix_insert_line($fixlinenr, $fixedline);
3858				$fixedline = $line;
3859				$fixedline =~ s/^(.\s*)\{\s*/$1/;
3860				fix_insert_line($fixlinenr, $fixedline);
3861			}
3862		}
3863
3864#
3865# Checks which are anchored on the added line.
3866#
3867
3868# check for malformed paths in #include statements (uses RAW line)
3869		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
3870			my $path = $1;
3871			if ($path =~ m{//}) {
3872				ERROR("MALFORMED_INCLUDE",
3873				      "malformed #include filename\n" . $herecurr);
3874			}
3875			if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
3876				ERROR("UAPI_INCLUDE",
3877				      "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
3878			}
3879		}
3880
3881# no C99 // comments
3882		if ($line =~ m{//}) {
3883			if (ERROR("C99_COMMENTS",
3884				  "do not use C99 // comments\n" . $herecurr) &&
3885			    $fix) {
3886				my $line = $fixed[$fixlinenr];
3887				if ($line =~ /\/\/(.*)$/) {
3888					my $comment = trim($1);
3889					$fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
3890				}
3891			}
3892		}
3893		# Remove C99 comments.
3894		$line =~ s@//.*@@;
3895		$opline =~ s@//.*@@;
3896
3897# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
3898# the whole statement.
3899#print "APW <$lines[$realline_next - 1]>\n";
3900		if (defined $realline_next &&
3901		    exists $lines[$realline_next - 1] &&
3902		    !defined $suppress_export{$realline_next} &&
3903		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3904		     $lines[$realline_next - 1] =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3905			# Handle definitions which produce identifiers with
3906			# a prefix:
3907			#   XXX(foo);
3908			#   EXPORT_SYMBOL(something_foo);
3909			my $name = $1;
3910			if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
3911			    $name =~ /^${Ident}_$2/) {
3912#print "FOO C name<$name>\n";
3913				$suppress_export{$realline_next} = 1;
3914
3915			} elsif ($stat !~ /(?:
3916				\n.}\s*$|
3917				^.DEFINE_$Ident\(\Q$name\E\)|
3918				^.DECLARE_$Ident\(\Q$name\E\)|
3919				^.LIST_HEAD\(\Q$name\E\)|
3920				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
3921				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
3922			    )/x) {
3923#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
3924				$suppress_export{$realline_next} = 2;
3925			} else {
3926				$suppress_export{$realline_next} = 1;
3927			}
3928		}
3929		if (!defined $suppress_export{$linenr} &&
3930		    $prevline =~ /^.\s*$/ &&
3931		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/ ||
3932		     $line =~ /EXPORT_UNUSED_SYMBOL.*\((.*)\)/)) {
3933#print "FOO B <$lines[$linenr - 1]>\n";
3934			$suppress_export{$linenr} = 2;
3935		}
3936		if (defined $suppress_export{$linenr} &&
3937		    $suppress_export{$linenr} == 2) {
3938			WARN("EXPORT_SYMBOL",
3939			     "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
3940		}
3941
3942# check for global initialisers.
3943		if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/) {
3944			if (ERROR("GLOBAL_INITIALISERS",
3945				  "do not initialise globals to $1\n" . $herecurr) &&
3946			    $fix) {
3947				$fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
3948			}
3949		}
3950# check for static initialisers.
3951		if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
3952			if (ERROR("INITIALISED_STATIC",
3953				  "do not initialise statics to $1\n" .
3954				      $herecurr) &&
3955			    $fix) {
3956				$fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
3957			}
3958		}
3959
3960# check for misordered declarations of char/short/int/long with signed/unsigned
3961		while ($sline =~ m{(\b$TypeMisordered\b)}g) {
3962			my $tmp = trim($1);
3963			WARN("MISORDERED_TYPE",
3964			     "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
3965		}
3966
3967# check for unnecessary <signed> int declarations of short/long/long long
3968		while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
3969			my $type = trim($1);
3970			next if ($type !~ /\bint\b/);
3971			next if ($type !~ /\b(?:short|long\s+long|long)\b/);
3972			my $new_type = $type;
3973			$new_type =~ s/\b\s*int\s*\b/ /;
3974			$new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
3975			$new_type =~ s/^const\s+//;
3976			$new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
3977			$new_type = "const $new_type" if ($type =~ /^const\b/);
3978			$new_type =~ s/\s+/ /g;
3979			$new_type = trim($new_type);
3980			if (WARN("UNNECESSARY_INT",
3981				 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
3982			    $fix) {
3983				$fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
3984			}
3985		}
3986
3987# check for static const char * arrays.
3988		if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
3989			WARN("STATIC_CONST_CHAR_ARRAY",
3990			     "static const char * array should probably be static const char * const\n" .
3991				$herecurr);
3992		}
3993
3994# check for initialized const char arrays that should be static const
3995		if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
3996			if (WARN("STATIC_CONST_CHAR_ARRAY",
3997				 "const array should probably be static const\n" . $herecurr) &&
3998			    $fix) {
3999				$fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4000			}
4001		}
4002
4003# check for static char foo[] = "bar" declarations.
4004		if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4005			WARN("STATIC_CONST_CHAR_ARRAY",
4006			     "static char array declaration should probably be static const char\n" .
4007				$herecurr);
4008		}
4009
4010# check for const <foo> const where <foo> is not a pointer or array type
4011		if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4012			my $found = $1;
4013			if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4014				WARN("CONST_CONST",
4015				     "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4016			} elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4017				WARN("CONST_CONST",
4018				     "'const $found const' should probably be 'const $found'\n" . $herecurr);
4019			}
4020		}
4021
4022# check for non-global char *foo[] = {"bar", ...} declarations.
4023		if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4024			WARN("STATIC_CONST_CHAR_ARRAY",
4025			     "char * array declaration might be better as static const\n" .
4026				$herecurr);
4027               }
4028
4029# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4030		if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4031			my $array = $1;
4032			if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4033				my $array_div = $1;
4034				if (WARN("ARRAY_SIZE",
4035					 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4036				    $fix) {
4037					$fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4038				}
4039			}
4040		}
4041
4042# check for function declarations without arguments like "int foo()"
4043		if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) {
4044			if (ERROR("FUNCTION_WITHOUT_ARGS",
4045				  "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4046			    $fix) {
4047				$fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4048			}
4049		}
4050
4051# check for new typedefs, only function parameters and sparse annotations
4052# make sense.
4053		if ($line =~ /\btypedef\s/ &&
4054		    $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4055		    $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4056		    $line !~ /\b$typeTypedefs\b/ &&
4057		    $line !~ /\b__bitwise\b/) {
4058			WARN("NEW_TYPEDEFS",
4059			     "do not add new typedefs\n" . $herecurr);
4060		}
4061
4062# * goes on variable not on type
4063		# (char*[ const])
4064		while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4065			#print "AA<$1>\n";
4066			my ($ident, $from, $to) = ($1, $2, $2);
4067
4068			# Should start with a space.
4069			$to =~ s/^(\S)/ $1/;
4070			# Should not end with a space.
4071			$to =~ s/\s+$//;
4072			# '*'s should not have spaces between.
4073			while ($to =~ s/\*\s+\*/\*\*/) {
4074			}
4075
4076##			print "1: from<$from> to<$to> ident<$ident>\n";
4077			if ($from ne $to) {
4078				if (ERROR("POINTER_LOCATION",
4079					  "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4080				    $fix) {
4081					my $sub_from = $ident;
4082					my $sub_to = $ident;
4083					$sub_to =~ s/\Q$from\E/$to/;
4084					$fixed[$fixlinenr] =~
4085					    s@\Q$sub_from\E@$sub_to@;
4086				}
4087			}
4088		}
4089		while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4090			#print "BB<$1>\n";
4091			my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4092
4093			# Should start with a space.
4094			$to =~ s/^(\S)/ $1/;
4095			# Should not end with a space.
4096			$to =~ s/\s+$//;
4097			# '*'s should not have spaces between.
4098			while ($to =~ s/\*\s+\*/\*\*/) {
4099			}
4100			# Modifiers should have spaces.
4101			$to =~ s/(\b$Modifier$)/$1 /;
4102
4103##			print "2: from<$from> to<$to> ident<$ident>\n";
4104			if ($from ne $to && $ident !~ /^$Modifier$/) {
4105				if (ERROR("POINTER_LOCATION",
4106					  "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4107				    $fix) {
4108
4109					my $sub_from = $match;
4110					my $sub_to = $match;
4111					$sub_to =~ s/\Q$from\E/$to/;
4112					$fixed[$fixlinenr] =~
4113					    s@\Q$sub_from\E@$sub_to@;
4114				}
4115			}
4116		}
4117
4118# avoid BUG() or BUG_ON()
4119		if ($line =~ /\b(?:BUG|BUG_ON)\b/) {
4120			my $msg_level = \&WARN;
4121			$msg_level = \&CHK if ($file);
4122			&{$msg_level}("AVOID_BUG",
4123				      "Avoid crashing the kernel - try using WARN_ON & recovery code rather than BUG() or BUG_ON()\n" . $herecurr);
4124		}
4125
4126# avoid LINUX_VERSION_CODE
4127		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4128			WARN("LINUX_VERSION_CODE",
4129			     "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4130		}
4131
4132		if(!$SOF) {
4133
4134# check for uses of printk_ratelimit
4135		if ($line =~ /\bprintk_ratelimit\s*\(/) {
4136			WARN("PRINTK_RATELIMITED",
4137			     "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4138		}
4139
4140# printk should use KERN_* levels
4141		if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4142			WARN("PRINTK_WITHOUT_KERN_LEVEL",
4143			     "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4144		}
4145
4146		if ($line =~ /\bprintk\s*\(\s*KERN_([A-Z]+)/) {
4147			my $orig = $1;
4148			my $level = lc($orig);
4149			$level = "warn" if ($level eq "warning");
4150			my $level2 = $level;
4151			$level2 = "dbg" if ($level eq "debug");
4152			WARN("PREFER_PR_LEVEL",
4153			     "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to printk(KERN_$orig ...\n" . $herecurr);
4154		}
4155
4156		if ($line =~ /\bpr_warning\s*\(/) {
4157			if (WARN("PREFER_PR_LEVEL",
4158				 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4159			    $fix) {
4160				$fixed[$fixlinenr] =~
4161				    s/\bpr_warning\b/pr_warn/;
4162			}
4163		}
4164
4165		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4166			my $orig = $1;
4167			my $level = lc($orig);
4168			$level = "warn" if ($level eq "warning");
4169			$level = "dbg" if ($level eq "debug");
4170			WARN("PREFER_DEV_LEVEL",
4171			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4172		}
4173
4174		} # !$SOF
4175
4176# ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4177# number of false positives, but assembly files are not checked, so at
4178# least the arch entry code will not trigger this warning.
4179		if ($line =~ /\bENOSYS\b/) {
4180			WARN("ENOSYS",
4181			     "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4182		}
4183
4184# function brace can't be on same line, except for #defines of do while,
4185# or if closed on same line
4186		if ($perl_version_ok &&
4187		    $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4188		    $sline !~ /\#\s*define\b.*do\s*\{/ &&
4189		    $sline !~ /}/) {
4190			if (ERROR("OPEN_BRACE",
4191				  "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4192			    $fix) {
4193				fix_delete_line($fixlinenr, $rawline);
4194				my $fixed_line = $rawline;
4195				$fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4196				my $line1 = $1;
4197				my $line2 = $2;
4198				fix_insert_line($fixlinenr, ltrim($line1));
4199				fix_insert_line($fixlinenr, "\+{");
4200				if ($line2 !~ /^\s*$/) {
4201					fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4202				}
4203			}
4204		}
4205
4206# open braces for enum, union and struct go on the same line.
4207		if ($line =~ /^.\s*{/ &&
4208		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4209			if (ERROR("OPEN_BRACE",
4210				  "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4211			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4212				fix_delete_line($fixlinenr - 1, $prevrawline);
4213				fix_delete_line($fixlinenr, $rawline);
4214				my $fixedline = rtrim($prevrawline) . " {";
4215				fix_insert_line($fixlinenr, $fixedline);
4216				$fixedline = $rawline;
4217				$fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4218				if ($fixedline !~ /^\+\s*$/) {
4219					fix_insert_line($fixlinenr, $fixedline);
4220				}
4221			}
4222		}
4223
4224# missing space after union, struct or enum definition
4225		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4226			if (WARN("SPACING",
4227				 "missing space after $1 definition\n" . $herecurr) &&
4228			    $fix) {
4229				$fixed[$fixlinenr] =~
4230				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4231			}
4232		}
4233
4234# Function pointer declarations
4235# check spacing between type, funcptr, and args
4236# canonical declaration is "type (*funcptr)(args...)"
4237		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4238			my $declare = $1;
4239			my $pre_pointer_space = $2;
4240			my $post_pointer_space = $3;
4241			my $funcname = $4;
4242			my $post_funcname_space = $5;
4243			my $pre_args_space = $6;
4244
4245# the $Declare variable will capture all spaces after the type
4246# so check it for a missing trailing missing space but pointer return types
4247# don't need a space so don't warn for those.
4248			my $post_declare_space = "";
4249			if ($declare =~ /(\s+)$/) {
4250				$post_declare_space = $1;
4251				$declare = rtrim($declare);
4252			}
4253			if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4254				WARN("SPACING",
4255				     "missing space after return type\n" . $herecurr);
4256				$post_declare_space = " ";
4257			}
4258
4259# unnecessary space "type  (*funcptr)(args...)"
4260# This test is not currently implemented because these declarations are
4261# equivalent to
4262#	int  foo(int bar, ...)
4263# and this is form shouldn't/doesn't generate a checkpatch warning.
4264#
4265#			elsif ($declare =~ /\s{2,}$/) {
4266#				WARN("SPACING",
4267#				     "Multiple spaces after return type\n" . $herecurr);
4268#			}
4269
4270# unnecessary space "type ( *funcptr)(args...)"
4271			if (defined $pre_pointer_space &&
4272			    $pre_pointer_space =~ /^\s/) {
4273				WARN("SPACING",
4274				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4275			}
4276
4277# unnecessary space "type (* funcptr)(args...)"
4278			if (defined $post_pointer_space &&
4279			    $post_pointer_space =~ /^\s/) {
4280				WARN("SPACING",
4281				     "Unnecessary space before function pointer name\n" . $herecurr);
4282			}
4283
4284# unnecessary space "type (*funcptr )(args...)"
4285			if (defined $post_funcname_space &&
4286			    $post_funcname_space =~ /^\s/) {
4287				WARN("SPACING",
4288				     "Unnecessary space after function pointer name\n" . $herecurr);
4289			}
4290
4291# unnecessary space "type (*funcptr) (args...)"
4292			if (defined $pre_args_space &&
4293			    $pre_args_space =~ /^\s/) {
4294				WARN("SPACING",
4295				     "Unnecessary space before function pointer arguments\n" . $herecurr);
4296			}
4297
4298			if (show_type("SPACING") && $fix) {
4299				$fixed[$fixlinenr] =~
4300				    s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4301			}
4302		}
4303
4304# check for spacing round square brackets; allowed:
4305#  1. with a type on the left -- int [] a;
4306#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4307#  3. inside a curly brace -- = { [0...10] = 5 }
4308		while ($line =~ /(.*?\s)\[/g) {
4309			my ($where, $prefix) = ($-[1], $1);
4310			if ($prefix !~ /$Type\s+$/ &&
4311			    ($where != 0 || $prefix !~ /^.\s+$/) &&
4312			    $prefix !~ /[{,:]\s+$/) {
4313				if (ERROR("BRACKET_SPACE",
4314					  "space prohibited before open square bracket '['\n" . $herecurr) &&
4315				    $fix) {
4316				    $fixed[$fixlinenr] =~
4317					s/^(\+.*?)\s+\[/$1\[/;
4318				}
4319			}
4320		}
4321
4322# check for spaces between functions and their parentheses.
4323		while ($line =~ /($Ident)\s+\(/g) {
4324			my $name = $1;
4325			my $ctx_before = substr($line, 0, $-[1]);
4326			my $ctx = "$ctx_before$name";
4327
4328			# Ignore those directives where spaces _are_ permitted.
4329			if ($name =~ /^(?:
4330				if|for|while|switch|return|case|
4331				volatile|__volatile__|
4332				__attribute__|format|__extension__|
4333				asm|__asm__)$/x)
4334			{
4335			# cpp #define statements have non-optional spaces, ie
4336			# if there is a space between the name and the open
4337			# parenthesis it is simply not a parameter group.
4338			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4339
4340			# cpp #elif statement condition may start with a (
4341			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4342
4343			# If this whole things ends with a type its most
4344			# likely a typedef for a function.
4345			} elsif ($ctx =~ /$Type$/) {
4346
4347			} else {
4348				if (WARN("SPACING",
4349					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4350					     $fix) {
4351					$fixed[$fixlinenr] =~
4352					    s/\b$name\s+\(/$name\(/;
4353				}
4354			}
4355		}
4356
4357# Check operator spacing.
4358		if (!($line=~/\#\s*include/)) {
4359			my $fixed_line = "";
4360			my $line_fixed = 0;
4361
4362			my $ops = qr{
4363				<<=|>>=|<=|>=|==|!=|
4364				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4365				=>|->|<<|>>|<|>|=|!|~|
4366				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4367				\?:|\?|:
4368			}x;
4369			my @elements = split(/($ops|;)/, $opline);
4370
4371##			print("element count: <" . $#elements . ">\n");
4372##			foreach my $el (@elements) {
4373##				print("el: <$el>\n");
4374##			}
4375
4376			my @fix_elements = ();
4377			my $off = 0;
4378
4379			foreach my $el (@elements) {
4380				push(@fix_elements, substr($rawline, $off, length($el)));
4381				$off += length($el);
4382			}
4383
4384			$off = 0;
4385
4386			my $blank = copy_spacing($opline);
4387			my $last_after = -1;
4388
4389			for (my $n = 0; $n < $#elements; $n += 2) {
4390
4391				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4392
4393##				print("n: <$n> good: <$good>\n");
4394
4395				$off += length($elements[$n]);
4396
4397				# Pick up the preceding and succeeding characters.
4398				my $ca = substr($opline, 0, $off);
4399				my $cc = '';
4400				if (length($opline) >= ($off + length($elements[$n + 1]))) {
4401					$cc = substr($opline, $off + length($elements[$n + 1]));
4402				}
4403				my $cb = "$ca$;$cc";
4404
4405				my $a = '';
4406				$a = 'V' if ($elements[$n] ne '');
4407				$a = 'W' if ($elements[$n] =~ /\s$/);
4408				$a = 'C' if ($elements[$n] =~ /$;$/);
4409				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4410				$a = 'O' if ($elements[$n] eq '');
4411				$a = 'E' if ($ca =~ /^\s*$/);
4412
4413				my $op = $elements[$n + 1];
4414
4415				my $c = '';
4416				if (defined $elements[$n + 2]) {
4417					$c = 'V' if ($elements[$n + 2] ne '');
4418					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
4419					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
4420					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4421					$c = 'O' if ($elements[$n + 2] eq '');
4422					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4423				} else {
4424					$c = 'E';
4425				}
4426
4427				my $ctx = "${a}x${c}";
4428
4429				my $at = "(ctx:$ctx)";
4430
4431				my $ptr = substr($blank, 0, $off) . "^";
4432				my $hereptr = "$hereline$ptr\n";
4433
4434				# Pull out the value of this operator.
4435				my $op_type = substr($curr_values, $off + 1, 1);
4436
4437				# Get the full operator variant.
4438				my $opv = $op . substr($curr_vars, $off, 1);
4439
4440				# Ignore operators passed as parameters.
4441				if ($op_type ne 'V' &&
4442				    $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4443
4444#				# Ignore comments
4445#				} elsif ($op =~ /^$;+$/) {
4446
4447				# ; should have either the end of line or a space or \ after it
4448				} elsif ($op eq ';') {
4449					if ($ctx !~ /.x[WEBC]/ &&
4450					    $cc !~ /^\\/ && $cc !~ /^;/) {
4451						if (ERROR("SPACING",
4452							  "space required after that '$op' $at\n" . $hereptr)) {
4453							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4454							$line_fixed = 1;
4455						}
4456					}
4457
4458				# // is a comment
4459				} elsif ($op eq '//') {
4460
4461				#   :   when part of a bitfield
4462				} elsif ($opv eq ':B') {
4463					# skip the bitfield test for now
4464
4465				# No spaces for:
4466				#   ->
4467				} elsif ($op eq '->') {
4468					if ($ctx =~ /Wx.|.xW/) {
4469						if (ERROR("SPACING",
4470							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4471							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4472							if (defined $fix_elements[$n + 2]) {
4473								$fix_elements[$n + 2] =~ s/^\s+//;
4474							}
4475							$line_fixed = 1;
4476						}
4477					}
4478
4479				# , must not have a space before and must have a space on the right.
4480				} elsif ($op eq ',') {
4481					my $rtrim_before = 0;
4482					my $space_after = 0;
4483					if ($ctx =~ /Wx./) {
4484						if (ERROR("SPACING",
4485							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4486							$line_fixed = 1;
4487							$rtrim_before = 1;
4488						}
4489					}
4490					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4491						if (ERROR("SPACING",
4492							  "space required after that '$op' $at\n" . $hereptr)) {
4493							$line_fixed = 1;
4494							$last_after = $n;
4495							$space_after = 1;
4496						}
4497					}
4498					if ($rtrim_before || $space_after) {
4499						if ($rtrim_before) {
4500							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4501						} else {
4502							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4503						}
4504						if ($space_after) {
4505							$good .= " ";
4506						}
4507					}
4508
4509				# '*' as part of a type definition -- reported already.
4510				} elsif ($opv eq '*_') {
4511					#warn "'*' is part of type\n";
4512
4513				# unary operators should have a space before and
4514				# none after.  May be left adjacent to another
4515				# unary operator, or a cast
4516				} elsif ($op eq '!' || $op eq '~' ||
4517					 $opv eq '*U' || $opv eq '-U' ||
4518					 $opv eq '&U' || $opv eq '&&U') {
4519					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4520						if (ERROR("SPACING",
4521							  "space required before that '$op' $at\n" . $hereptr)) {
4522							if ($n != $last_after + 2) {
4523								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4524								$line_fixed = 1;
4525							}
4526						}
4527					}
4528					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4529						# A unary '*' may be const
4530
4531					} elsif ($ctx =~ /.xW/) {
4532						if (ERROR("SPACING",
4533							  "space prohibited after that '$op' $at\n" . $hereptr)) {
4534							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4535							if (defined $fix_elements[$n + 2]) {
4536								$fix_elements[$n + 2] =~ s/^\s+//;
4537							}
4538							$line_fixed = 1;
4539						}
4540					}
4541
4542				# unary ++ and unary -- are allowed no space on one side.
4543				} elsif ($op eq '++' or $op eq '--') {
4544					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4545						if (ERROR("SPACING",
4546							  "space required one side of that '$op' $at\n" . $hereptr)) {
4547							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4548							$line_fixed = 1;
4549						}
4550					}
4551					if ($ctx =~ /Wx[BE]/ ||
4552					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4553						if (ERROR("SPACING",
4554							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4555							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4556							$line_fixed = 1;
4557						}
4558					}
4559					if ($ctx =~ /ExW/) {
4560						if (ERROR("SPACING",
4561							  "space prohibited after that '$op' $at\n" . $hereptr)) {
4562							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4563							if (defined $fix_elements[$n + 2]) {
4564								$fix_elements[$n + 2] =~ s/^\s+//;
4565							}
4566							$line_fixed = 1;
4567						}
4568					}
4569
4570				# << and >> may either have or not have spaces both sides
4571				} elsif ($op eq '<<' or $op eq '>>' or
4572					 $op eq '&' or $op eq '^' or $op eq '|' or
4573					 $op eq '+' or $op eq '-' or
4574					 $op eq '*' or $op eq '/' or
4575					 $op eq '%')
4576				{
4577					if ($check) {
4578						if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4579							if (CHK("SPACING",
4580								"spaces preferred around that '$op' $at\n" . $hereptr)) {
4581								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4582								$fix_elements[$n + 2] =~ s/^\s+//;
4583								$line_fixed = 1;
4584							}
4585						} elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4586							if (CHK("SPACING",
4587								"space preferred before that '$op' $at\n" . $hereptr)) {
4588								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4589								$line_fixed = 1;
4590							}
4591						}
4592					} elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4593						if (ERROR("SPACING",
4594							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
4595							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4596							if (defined $fix_elements[$n + 2]) {
4597								$fix_elements[$n + 2] =~ s/^\s+//;
4598							}
4599							$line_fixed = 1;
4600						}
4601					}
4602
4603				# A colon needs no spaces before when it is
4604				# terminating a case value or a label.
4605				} elsif ($opv eq ':C' || $opv eq ':L') {
4606					if ($ctx =~ /Wx./) {
4607						if (ERROR("SPACING",
4608							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4609							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4610							$line_fixed = 1;
4611						}
4612					}
4613
4614				# All the others need spaces both sides.
4615				} elsif ($ctx !~ /[EWC]x[CWE]/) {
4616					my $ok = 0;
4617
4618					# Ignore email addresses <foo@bar>
4619					if (($op eq '<' &&
4620					     $cc =~ /^\S+\@\S+>/) ||
4621					    ($op eq '>' &&
4622					     $ca =~ /<\S+\@\S+$/))
4623					{
4624					    	$ok = 1;
4625					}
4626
4627					# for asm volatile statements
4628					# ignore a colon with another
4629					# colon immediately before or after
4630					if (($op eq ':') &&
4631					    ($ca =~ /:$/ || $cc =~ /^:/)) {
4632						$ok = 1;
4633					}
4634
4635					# messages are ERROR, but ?: are CHK
4636					if ($ok == 0) {
4637						my $msg_level = \&ERROR;
4638						$msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4639
4640						if (&{$msg_level}("SPACING",
4641								  "spaces required around that '$op' $at\n" . $hereptr)) {
4642							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4643							if (defined $fix_elements[$n + 2]) {
4644								$fix_elements[$n + 2] =~ s/^\s+//;
4645							}
4646							$line_fixed = 1;
4647						}
4648					}
4649				}
4650				$off += length($elements[$n + 1]);
4651
4652##				print("n: <$n> GOOD: <$good>\n");
4653
4654				$fixed_line = $fixed_line . $good;
4655			}
4656
4657			if (($#elements % 2) == 0) {
4658				$fixed_line = $fixed_line . $fix_elements[$#elements];
4659			}
4660
4661			if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4662				$fixed[$fixlinenr] = $fixed_line;
4663			}
4664
4665
4666		}
4667
4668# check for whitespace before a non-naked semicolon
4669		if ($line =~ /^\+.*\S\s+;\s*$/) {
4670			if (WARN("SPACING",
4671				 "space prohibited before semicolon\n" . $herecurr) &&
4672			    $fix) {
4673				1 while $fixed[$fixlinenr] =~
4674				    s/^(\+.*\S)\s+;/$1;/;
4675			}
4676		}
4677
4678# check for multiple assignments
4679		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4680			CHK("MULTIPLE_ASSIGNMENTS",
4681			    "multiple assignments should be avoided\n" . $herecurr);
4682		}
4683
4684## # check for multiple declarations, allowing for a function declaration
4685## # continuation.
4686## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4687## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4688##
4689## 			# Remove any bracketed sections to ensure we do not
4690## 			# falsly report the parameters of functions.
4691## 			my $ln = $line;
4692## 			while ($ln =~ s/\([^\(\)]*\)//g) {
4693## 			}
4694## 			if ($ln =~ /,/) {
4695## 				WARN("MULTIPLE_DECLARATION",
4696##				     "declaring multiple variables together should be avoided\n" . $herecurr);
4697## 			}
4698## 		}
4699
4700#need space before brace following if, while, etc
4701		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4702		    $line =~ /\b(?:else|do)\{/) {
4703			if (ERROR("SPACING",
4704				  "space required before the open brace '{'\n" . $herecurr) &&
4705			    $fix) {
4706				$fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4707			}
4708		}
4709
4710## # check for blank lines before declarations
4711##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4712##		    $prevrawline =~ /^.\s*$/) {
4713##			WARN("SPACING",
4714##			     "No blank lines before declarations\n" . $hereprev);
4715##		}
4716##
4717
4718# closing brace should have a space following it when it has anything
4719# on the line
4720		if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4721			if (ERROR("SPACING",
4722				  "space required after that close brace '}'\n" . $herecurr) &&
4723			    $fix) {
4724				$fixed[$fixlinenr] =~
4725				    s/}((?!(?:,|;|\)))\S)/} $1/;
4726			}
4727		}
4728
4729# check spacing on square brackets
4730		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4731			if (ERROR("SPACING",
4732				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
4733			    $fix) {
4734				$fixed[$fixlinenr] =~
4735				    s/\[\s+/\[/;
4736			}
4737		}
4738		if ($line =~ /\s\]/) {
4739			if (ERROR("SPACING",
4740				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4741			    $fix) {
4742				$fixed[$fixlinenr] =~
4743				    s/\s+\]/\]/;
4744			}
4745		}
4746
4747# check spacing on parentheses
4748		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4749		    $line !~ /for\s*\(\s+;/) {
4750			if (ERROR("SPACING",
4751				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4752			    $fix) {
4753				$fixed[$fixlinenr] =~
4754				    s/\(\s+/\(/;
4755			}
4756		}
4757		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4758		    $line !~ /for\s*\(.*;\s+\)/ &&
4759		    $line !~ /:\s+\)/) {
4760			if (ERROR("SPACING",
4761				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4762			    $fix) {
4763				$fixed[$fixlinenr] =~
4764				    s/\s+\)/\)/;
4765			}
4766		}
4767
4768# check unnecessary parentheses around addressof/dereference single $Lvals
4769# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4770
4771		while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4772			my $var = $1;
4773			if (CHK("UNNECESSARY_PARENTHESES",
4774				"Unnecessary parentheses around $var\n" . $herecurr) &&
4775			    $fix) {
4776				$fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4777			}
4778		}
4779
4780# check for unnecessary parentheses around function pointer uses
4781# ie: (foo->bar)(); should be foo->bar();
4782# but not "if (foo->bar) (" to avoid some false positives
4783		if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4784			my $var = $2;
4785			if (CHK("UNNECESSARY_PARENTHESES",
4786				"Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4787			    $fix) {
4788				my $var2 = deparenthesize($var);
4789				$var2 =~ s/\s//g;
4790				$fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4791			}
4792		}
4793
4794# check for unnecessary parentheses around comparisons in if uses
4795# when !drivers/staging or command-line uses --strict
4796		if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4797		    $perl_version_ok && defined($stat) &&
4798		    $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4799			my $if_stat = $1;
4800			my $test = substr($2, 1, -1);
4801			my $herectx;
4802			while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4803				my $match = $1;
4804				# avoid parentheses around potential macro args
4805				next if ($match =~ /^\s*\w+\s*$/);
4806				if (!defined($herectx)) {
4807					$herectx = $here . "\n";
4808					my $cnt = statement_rawlines($if_stat);
4809					for (my $n = 0; $n < $cnt; $n++) {
4810						my $rl = raw_line($linenr, $n);
4811						$herectx .=  $rl . "\n";
4812						last if $rl =~ /^[ \+].*\{/;
4813					}
4814				}
4815				CHK("UNNECESSARY_PARENTHESES",
4816				    "Unnecessary parentheses around '$match'\n" . $herectx);
4817			}
4818		}
4819
4820#goto labels aren't indented, allow a single space however
4821		if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4822		   !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4823			if (WARN("INDENTED_LABEL",
4824				 "labels should not be indented\n" . $herecurr) &&
4825			    $fix) {
4826				$fixed[$fixlinenr] =~
4827				    s/^(.)\s+/$1/;
4828			}
4829		}
4830
4831# return is not a function
4832		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4833			my $spacing = $1;
4834			if ($perl_version_ok &&
4835			    $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4836				my $value = $1;
4837				$value = deparenthesize($value);
4838				if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4839					ERROR("RETURN_PARENTHESES",
4840					      "return is not a function, parentheses are not required\n" . $herecurr);
4841				}
4842			} elsif ($spacing !~ /\s+/) {
4843				ERROR("SPACING",
4844				      "space required before the open parenthesis '('\n" . $herecurr);
4845			}
4846		}
4847
4848# unnecessary return in a void function
4849# at end-of-function, with the previous line a single leading tab, then return;
4850# and the line before that not a goto label target like "out:"
4851		if ($sline =~ /^[ \+]}\s*$/ &&
4852		    $prevline =~ /^\+\treturn\s*;\s*$/ &&
4853		    $linenr >= 3 &&
4854		    $lines[$linenr - 3] =~ /^[ +]/ &&
4855		    $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4856			WARN("RETURN_VOID",
4857			     "void function return statements are not generally useful\n" . $hereprev);
4858               }
4859
4860# if statements using unnecessary parentheses - ie: if ((foo == bar))
4861		if ($perl_version_ok &&
4862		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
4863			my $openparens = $1;
4864			my $count = $openparens =~ tr@\(@\(@;
4865			my $msg = "";
4866			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4867				my $comp = $4;	#Not $1 because of $LvalOrFunc
4868				$msg = " - maybe == should be = ?" if ($comp eq "==");
4869				WARN("UNNECESSARY_PARENTHESES",
4870				     "Unnecessary parentheses$msg\n" . $herecurr);
4871			}
4872		}
4873
4874# comparisons with a constant or upper case identifier on the left
4875#	avoid cases like "foo + BAR < baz"
4876#	only fix matches surrounded by parentheses to avoid incorrect
4877#	conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4878		if ($perl_version_ok &&
4879		    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4880			my $lead = $1;
4881			my $const = $2;
4882			my $comp = $3;
4883			my $to = $4;
4884			my $newcomp = $comp;
4885			if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4886			    $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4887			    WARN("CONSTANT_COMPARISON",
4888				 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4889			    $fix) {
4890				if ($comp eq "<") {
4891					$newcomp = ">";
4892				} elsif ($comp eq "<=") {
4893					$newcomp = ">=";
4894				} elsif ($comp eq ">") {
4895					$newcomp = "<";
4896				} elsif ($comp eq ">=") {
4897					$newcomp = "<=";
4898				}
4899				$fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4900			}
4901		}
4902
4903# Return of what appears to be an errno should normally be negative
4904		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4905			my $name = $1;
4906			if ($name ne 'EOF' && $name ne 'ERROR') {
4907				WARN("USE_NEGATIVE_ERRNO",
4908				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4909			}
4910		}
4911
4912# Need a space before open parenthesis after if, while etc
4913		if ($line =~ /\b(if|while|for|switch)\(/) {
4914			if (ERROR("SPACING",
4915				  "space required before the open parenthesis '('\n" . $herecurr) &&
4916			    $fix) {
4917				$fixed[$fixlinenr] =~
4918				    s/\b(if|while|for|switch)\(/$1 \(/;
4919			}
4920		}
4921
4922# Check for illegal assignment in if conditional -- and check for trailing
4923# statements after the conditional.
4924		if ($line =~ /do\s*(?!{)/) {
4925			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4926				ctx_statement_block($linenr, $realcnt, 0)
4927					if (!defined $stat);
4928			my ($stat_next) = ctx_statement_block($line_nr_next,
4929						$remain_next, $off_next);
4930			$stat_next =~ s/\n./\n /g;
4931			##print "stat<$stat> stat_next<$stat_next>\n";
4932
4933			if ($stat_next =~ /^\s*while\b/) {
4934				# If the statement carries leading newlines,
4935				# then count those as offsets.
4936				my ($whitespace) =
4937					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4938				my $offset =
4939					statement_rawlines($whitespace) - 1;
4940
4941				$suppress_whiletrailers{$line_nr_next +
4942								$offset} = 1;
4943			}
4944		}
4945		if (!defined $suppress_whiletrailers{$linenr} &&
4946		    defined($stat) && defined($cond) &&
4947		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4948			my ($s, $c) = ($stat, $cond);
4949
4950			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4951				ERROR("ASSIGN_IN_IF",
4952				      "do not use assignment in if condition\n" . $herecurr);
4953			}
4954
4955			# Find out what is on the end of the line after the
4956			# conditional.
4957			substr($s, 0, length($c), '');
4958			$s =~ s/\n.*//g;
4959			$s =~ s/$;//g; 	# Remove any comments
4960			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4961			    $c !~ /}\s*while\s*/)
4962			{
4963				# Find out how long the conditional actually is.
4964				my @newlines = ($c =~ /\n/gs);
4965				my $cond_lines = 1 + $#newlines;
4966				my $stat_real = '';
4967
4968				$stat_real = raw_line($linenr, $cond_lines)
4969							. "\n" if ($cond_lines);
4970				if (defined($stat_real) && $cond_lines > 1) {
4971					$stat_real = "[...]\n$stat_real";
4972				}
4973
4974				ERROR("TRAILING_STATEMENTS",
4975				      "trailing statements should be on next line\n" . $herecurr . $stat_real);
4976			}
4977		}
4978
4979# Check for bitwise tests written as boolean
4980		if ($line =~ /
4981			(?:
4982				(?:\[|\(|\&\&|\|\|)
4983				\s*0[xX][0-9]+\s*
4984				(?:\&\&|\|\|)
4985			|
4986				(?:\&\&|\|\|)
4987				\s*0[xX][0-9]+\s*
4988				(?:\&\&|\|\||\)|\])
4989			)/x)
4990		{
4991			WARN("HEXADECIMAL_BOOLEAN_TEST",
4992			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4993		}
4994
4995# if and else should not have general statements after it
4996		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4997			my $s = $1;
4998			$s =~ s/$;//g; 	# Remove any comments
4999			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5000				ERROR("TRAILING_STATEMENTS",
5001				      "trailing statements should be on next line\n" . $herecurr);
5002			}
5003		}
5004# if should not continue a brace
5005		if ($line =~ /}\s*if\b/) {
5006			ERROR("TRAILING_STATEMENTS",
5007			      "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5008				$herecurr);
5009		}
5010# case and default should not have general statements after them
5011		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5012		    $line !~ /\G(?:
5013			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5014			\s*return\s+
5015		    )/xg)
5016		{
5017			ERROR("TRAILING_STATEMENTS",
5018			      "trailing statements should be on next line\n" . $herecurr);
5019		}
5020
5021		# Check for }<nl>else {, these must be at the same
5022		# indent level to be relevant to each other.
5023		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5024		    $previndent == $indent) {
5025			if (ERROR("ELSE_AFTER_BRACE",
5026				  "else should follow close brace '}'\n" . $hereprev) &&
5027			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5028				fix_delete_line($fixlinenr - 1, $prevrawline);
5029				fix_delete_line($fixlinenr, $rawline);
5030				my $fixedline = $prevrawline;
5031				$fixedline =~ s/}\s*$//;
5032				if ($fixedline !~ /^\+\s*$/) {
5033					fix_insert_line($fixlinenr, $fixedline);
5034				}
5035				$fixedline = $rawline;
5036				$fixedline =~ s/^(.\s*)else/$1} else/;
5037				fix_insert_line($fixlinenr, $fixedline);
5038			}
5039		}
5040
5041		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5042		    $previndent == $indent) {
5043			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5044
5045			# Find out what is on the end of the line after the
5046			# conditional.
5047			substr($s, 0, length($c), '');
5048			$s =~ s/\n.*//g;
5049
5050			if ($s =~ /^\s*;/) {
5051				if (ERROR("WHILE_AFTER_BRACE",
5052					  "while should follow close brace '}'\n" . $hereprev) &&
5053				    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5054					fix_delete_line($fixlinenr - 1, $prevrawline);
5055					fix_delete_line($fixlinenr, $rawline);
5056					my $fixedline = $prevrawline;
5057					my $trailing = $rawline;
5058					$trailing =~ s/^\+//;
5059					$trailing = trim($trailing);
5060					$fixedline =~ s/}\s*$/} $trailing/;
5061					fix_insert_line($fixlinenr, $fixedline);
5062				}
5063			}
5064		}
5065
5066#Specific variable tests
5067		while ($line =~ m{($Constant|$Lval)}g) {
5068			my $var = $1;
5069
5070#CamelCase
5071			if ($var !~ /^$Constant$/ &&
5072			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5073#Ignore Page<foo> variants
5074			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5075#Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show)
5076			    $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/ &&
5077#Ignore some three character SI units explicitly, like MiB and KHz
5078			    $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5079				while ($var =~ m{($Ident)}g) {
5080					my $word = $1;
5081					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5082					if ($check) {
5083						seed_camelcase_includes();
5084						if (!$file && !$camelcase_file_seeded) {
5085							seed_camelcase_file($realfile);
5086							$camelcase_file_seeded = 1;
5087						}
5088					}
5089					if (!defined $camelcase{$word}) {
5090						$camelcase{$word} = 1;
5091						CHK("CAMELCASE",
5092						    "Avoid CamelCase: <$word>\n" . $herecurr);
5093					}
5094				}
5095			}
5096		}
5097
5098#no spaces allowed after \ in define
5099		if ($line =~ /\#\s*define.*\\\s+$/) {
5100			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5101				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5102			    $fix) {
5103				$fixed[$fixlinenr] =~ s/\s+$//;
5104			}
5105		}
5106
5107# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5108# itself <asm/foo.h> (uses RAW line)
5109		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5110			my $file = "$1.h";
5111			my $checkfile = "include/linux/$file";
5112			if (-f "$root/$checkfile" &&
5113			    $realfile ne $checkfile &&
5114			    $1 !~ /$allowed_asm_includes/)
5115			{
5116				my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5117				if ($asminclude > 0) {
5118					if ($realfile =~ m{^arch/}) {
5119						CHK("ARCH_INCLUDE_LINUX",
5120						    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5121					} else {
5122						WARN("INCLUDE_LINUX",
5123						     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5124					}
5125				}
5126			}
5127		}
5128
5129# multi-statement macros should be enclosed in a do while loop, grab the
5130# first statement and ensure its the whole macro if its not enclosed
5131# in a known good container
5132		if ($realfile !~ m@/vmlinux.lds.h$@ &&
5133		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5134			my $ln = $linenr;
5135			my $cnt = $realcnt;
5136			my ($off, $dstat, $dcond, $rest);
5137			my $ctx = '';
5138			my $has_flow_statement = 0;
5139			my $has_arg_concat = 0;
5140			($dstat, $dcond, $ln, $cnt, $off) =
5141				ctx_statement_block($linenr, $realcnt, 0);
5142			$ctx = $dstat;
5143			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5144			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5145
5146			$has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5147			$has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5148
5149			$dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5150			my $define_args = $1;
5151			my $define_stmt = $dstat;
5152			my @def_args = ();
5153
5154			if (defined $define_args && $define_args ne "") {
5155				$define_args = substr($define_args, 1, length($define_args) - 2);
5156				$define_args =~ s/\s*//g;
5157				$define_args =~ s/\\\+?//g;
5158				@def_args = split(",", $define_args);
5159			}
5160
5161			$dstat =~ s/$;//g;
5162			$dstat =~ s/\\\n.//g;
5163			$dstat =~ s/^\s*//s;
5164			$dstat =~ s/\s*$//s;
5165
5166			# Flatten any parentheses and braces
5167			while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5168			       $dstat =~ s/\{[^\{\}]*\}/1/ ||
5169			       $dstat =~ s/.\[[^\[\]]*\]/1/)
5170			{
5171			}
5172
5173			# Flatten any obvious string concatentation.
5174			while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5175			       $dstat =~ s/$Ident\s*($String)/$1/)
5176			{
5177			}
5178
5179			# Make asm volatile uses seem like a generic function
5180			$dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5181
5182			my $exceptions = qr{
5183				$Declare|
5184				module_param_named|
5185				MODULE_PARM_DESC|
5186				DECLARE_PER_CPU|
5187				DEFINE_PER_CPU|
5188				__typeof__\(|
5189				union|
5190				struct|
5191				\.$Ident\s*=\s*|
5192				^\"|\"$|
5193				^\[
5194			}x;
5195			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5196
5197			$ctx =~ s/\n*$//;
5198			my $stmt_cnt = statement_rawlines($ctx);
5199			my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5200
5201			if ($dstat ne '' &&
5202			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
5203			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
5204			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5205			    $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&			# character constants
5206			    $dstat !~ /$exceptions/ &&
5207			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
5208			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
5209			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
5210			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
5211			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
5212			    $dstat !~ /^do\s*{/ &&					# do {...
5213			    $dstat !~ /^\(\{/ &&						# ({...
5214			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5215			{
5216				if ($dstat =~ /^\s*if\b/) {
5217					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5218					      "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5219				} elsif ($dstat =~ /;/) {
5220					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5221					      "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5222				} else {
5223					ERROR("COMPLEX_MACRO",
5224					      "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5225				}
5226
5227			}
5228
5229			# Make $define_stmt single line, comment-free, etc
5230			my @stmt_array = split('\n', $define_stmt);
5231			my $first = 1;
5232			$define_stmt = "";
5233			foreach my $l (@stmt_array) {
5234				$l =~ s/\\$//;
5235				if ($first) {
5236					$define_stmt = $l;
5237					$first = 0;
5238				} elsif ($l =~ /^[\+ ]/) {
5239					$define_stmt .= substr($l, 1);
5240				}
5241			}
5242			$define_stmt =~ s/$;//g;
5243			$define_stmt =~ s/\s+/ /g;
5244			$define_stmt = trim($define_stmt);
5245
5246# check if any macro arguments are reused (ignore '...' and 'type')
5247			foreach my $arg (@def_args) {
5248			        next if ($arg =~ /\.\.\./);
5249			        next if ($arg =~ /^type$/i);
5250				my $tmp_stmt = $define_stmt;
5251				$tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5252				$tmp_stmt =~ s/\#+\s*$arg\b//g;
5253				$tmp_stmt =~ s/\b$arg\s*\#\#//g;
5254				my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5255				if ($use_cnt > 1) {
5256					CHK("MACRO_ARG_REUSE",
5257					    "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5258				    }
5259# check if any macro arguments may have other precedence issues
5260				if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5261				    ((defined($1) && $1 ne ',') ||
5262				     (defined($2) && $2 ne ','))) {
5263					CHK("MACRO_ARG_PRECEDENCE",
5264					    "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5265				}
5266			}
5267
5268# check for macros with flow control, but without ## concatenation
5269# ## concatenation is commonly a macro that defines a function so ignore those
5270			if ($has_flow_statement && !$has_arg_concat) {
5271				my $cnt = statement_rawlines($ctx);
5272				my $herectx = get_stat_here($linenr, $cnt, $here);
5273
5274				WARN("MACRO_WITH_FLOW_CONTROL",
5275				     "Macros with flow control statements should be avoided\n" . "$herectx");
5276			}
5277
5278# check for line continuations outside of #defines, preprocessor #, and asm
5279
5280		} else {
5281			if ($prevline !~ /^..*\\$/ &&
5282			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
5283			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
5284			    $line =~ /^\+.*\\$/) {
5285				WARN("LINE_CONTINUATIONS",
5286				     "Avoid unnecessary line continuations\n" . $herecurr);
5287			}
5288		}
5289
5290# do {} while (0) macro tests:
5291# single-statement macros do not need to be enclosed in do while (0) loop,
5292# macro should not end with a semicolon
5293		if ($perl_version_ok &&
5294		    $realfile !~ m@/vmlinux.lds.h$@ &&
5295		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5296			my $ln = $linenr;
5297			my $cnt = $realcnt;
5298			my ($off, $dstat, $dcond, $rest);
5299			my $ctx = '';
5300			($dstat, $dcond, $ln, $cnt, $off) =
5301				ctx_statement_block($linenr, $realcnt, 0);
5302			$ctx = $dstat;
5303
5304			$dstat =~ s/\\\n.//g;
5305			$dstat =~ s/$;/ /g;
5306
5307			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5308				my $stmts = $2;
5309				my $semis = $3;
5310
5311				$ctx =~ s/\n*$//;
5312				my $cnt = statement_rawlines($ctx);
5313				my $herectx = get_stat_here($linenr, $cnt, $here);
5314
5315				if (($stmts =~ tr/;/;/) == 1 &&
5316				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
5317					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5318					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5319				}
5320				if (defined $semis && $semis ne "") {
5321					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5322					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5323				}
5324			} elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5325				$ctx =~ s/\n*$//;
5326				my $cnt = statement_rawlines($ctx);
5327				my $herectx = get_stat_here($linenr, $cnt, $here);
5328
5329				WARN("TRAILING_SEMICOLON",
5330				     "macros should not use a trailing semicolon\n" . "$herectx");
5331			}
5332		}
5333
5334# check for redundant bracing round if etc
5335		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5336			my ($level, $endln, @chunks) =
5337				ctx_statement_full($linenr, $realcnt, 1);
5338			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5339			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5340			if ($#chunks > 0 && $level == 0) {
5341				my @allowed = ();
5342				my $allow = 0;
5343				my $seen = 0;
5344				my $herectx = $here . "\n";
5345				my $ln = $linenr - 1;
5346				for my $chunk (@chunks) {
5347					my ($cond, $block) = @{$chunk};
5348
5349					# If the condition carries leading newlines, then count those as offsets.
5350					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5351					my $offset = statement_rawlines($whitespace) - 1;
5352
5353					$allowed[$allow] = 0;
5354					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5355
5356					# We have looked at and allowed this specific line.
5357					$suppress_ifbraces{$ln + $offset} = 1;
5358
5359					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5360					$ln += statement_rawlines($block) - 1;
5361
5362					substr($block, 0, length($cond), '');
5363
5364					$seen++ if ($block =~ /^\s*{/);
5365
5366					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5367					if (statement_lines($cond) > 1) {
5368						#print "APW: ALLOWED: cond<$cond>\n";
5369						$allowed[$allow] = 1;
5370					}
5371					if ($block =~/\b(?:if|for|while)\b/) {
5372						#print "APW: ALLOWED: block<$block>\n";
5373						$allowed[$allow] = 1;
5374					}
5375					if (statement_block_size($block) > 1) {
5376						#print "APW: ALLOWED: lines block<$block>\n";
5377						$allowed[$allow] = 1;
5378					}
5379					$allow++;
5380				}
5381				if ($seen) {
5382					my $sum_allowed = 0;
5383					foreach (@allowed) {
5384						$sum_allowed += $_;
5385					}
5386					if ($sum_allowed == 0) {
5387						WARN("BRACES",
5388						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
5389					} elsif ($sum_allowed != $allow &&
5390						 $seen != $allow) {
5391						CHK("BRACES",
5392						    "braces {} should be used on all arms of this statement\n" . $herectx);
5393					}
5394				}
5395			}
5396		}
5397		if (!defined $suppress_ifbraces{$linenr - 1} &&
5398					$line =~ /\b(if|while|for|else)\b/) {
5399			my $allowed = 0;
5400
5401			# Check the pre-context.
5402			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5403				#print "APW: ALLOWED: pre<$1>\n";
5404				$allowed = 1;
5405			}
5406
5407			my ($level, $endln, @chunks) =
5408				ctx_statement_full($linenr, $realcnt, $-[0]);
5409
5410			# Check the condition.
5411			my ($cond, $block) = @{$chunks[0]};
5412			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5413			if (defined $cond) {
5414				substr($block, 0, length($cond), '');
5415			}
5416			if (statement_lines($cond) > 1) {
5417				#print "APW: ALLOWED: cond<$cond>\n";
5418				$allowed = 1;
5419			}
5420			if ($block =~/\b(?:if|for|while)\b/) {
5421				#print "APW: ALLOWED: block<$block>\n";
5422				$allowed = 1;
5423			}
5424			if (statement_block_size($block) > 1) {
5425				#print "APW: ALLOWED: lines block<$block>\n";
5426				$allowed = 1;
5427			}
5428			# Check the post-context.
5429			if (defined $chunks[1]) {
5430				my ($cond, $block) = @{$chunks[1]};
5431				if (defined $cond) {
5432					substr($block, 0, length($cond), '');
5433				}
5434				if ($block =~ /^\s*\{/) {
5435					#print "APW: ALLOWED: chunk-1 block<$block>\n";
5436					$allowed = 1;
5437				}
5438			}
5439			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5440				my $cnt = statement_rawlines($block);
5441				my $herectx = get_stat_here($linenr, $cnt, $here);
5442
5443				WARN("BRACES",
5444				     "braces {} are not necessary for single statement blocks\n" . $herectx);
5445			}
5446		}
5447
5448# check for single line unbalanced braces
5449		if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5450		    $sline =~ /^.\s*else\s*\{\s*$/) {
5451			CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5452		}
5453
5454# check for unnecessary blank lines around braces
5455		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5456			if (CHK("BRACES",
5457				"Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5458			    $fix && $prevrawline =~ /^\+/) {
5459				fix_delete_line($fixlinenr - 1, $prevrawline);
5460			}
5461		}
5462		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5463			if (CHK("BRACES",
5464				"Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5465			    $fix) {
5466				fix_delete_line($fixlinenr, $rawline);
5467			}
5468		}
5469
5470# no volatiles please
5471		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5472		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5473			WARN("VOLATILE",
5474			     "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5475		}
5476
5477# Check for user-visible strings broken across lines, which breaks the ability
5478# to grep for the string.  Make exceptions when the previous string ends in a
5479# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5480# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5481		if ($line =~ /^\+\s*$String/ &&
5482		    $prevline =~ /"\s*$/ &&
5483		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5484			if (WARN("SPLIT_STRING",
5485				 "quoted string split across lines\n" . $hereprev) &&
5486				     $fix &&
5487				     $prevrawline =~ /^\+.*"\s*$/ &&
5488				     $last_coalesced_string_linenr != $linenr - 1) {
5489				my $extracted_string = get_quoted_string($line, $rawline);
5490				my $comma_close = "";
5491				if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5492					$comma_close = $1;
5493				}
5494
5495				fix_delete_line($fixlinenr - 1, $prevrawline);
5496				fix_delete_line($fixlinenr, $rawline);
5497				my $fixedline = $prevrawline;
5498				$fixedline =~ s/"\s*$//;
5499				$fixedline .= substr($extracted_string, 1) . trim($comma_close);
5500				fix_insert_line($fixlinenr - 1, $fixedline);
5501				$fixedline = $rawline;
5502				$fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5503				if ($fixedline !~ /\+\s*$/) {
5504					fix_insert_line($fixlinenr, $fixedline);
5505				}
5506				$last_coalesced_string_linenr = $linenr;
5507			}
5508		}
5509
5510# check for missing a space in a string concatenation
5511		if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5512			WARN('MISSING_SPACE',
5513			     "break quoted strings at a space character\n" . $hereprev);
5514		}
5515
5516# check for an embedded function name in a string when the function is known
5517# This does not work very well for -f --file checking as it depends on patch
5518# context providing the function name or a single line form for in-file
5519# function declarations
5520		if (!$SOF &&
5521		    $line =~ /^\+.*$String/ &&
5522		    defined($context_function) &&
5523		    get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5524		    length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5525			WARN("EMBEDDED_FUNCTION_NAME",
5526			     "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5527		}
5528
5529# check for spaces before a quoted newline
5530		if ($rawline =~ /^.*\".*\s\\n/) {
5531			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5532				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5533			    $fix) {
5534				$fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5535			}
5536
5537		}
5538
5539# concatenated string without spaces between elements
5540		if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5541			if (CHK("CONCATENATED_STRING",
5542				"Concatenated strings should use spaces between elements\n" . $herecurr) &&
5543			    $fix) {
5544				while ($line =~ /($String)/g) {
5545					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5546					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5547					$fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5548				}
5549			}
5550		}
5551
5552# uncoalesced string fragments
5553		if ($line =~ /$String\s*"/) {
5554			if (WARN("STRING_FRAGMENTS",
5555				 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5556			    $fix) {
5557				while ($line =~ /($String)(?=\s*")/g) {
5558					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5559					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5560				}
5561			}
5562		}
5563
5564# check for non-standard and hex prefixed decimal printf formats
5565		my $show_L = 1;	#don't show the same defect twice
5566		my $show_Z = 1;
5567		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5568			my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5569			$string =~ s/%%/__/g;
5570			# check for %L
5571			if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5572				WARN("PRINTF_L",
5573				     "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5574				$show_L = 0;
5575			}
5576			# check for %Z
5577			if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5578				WARN("PRINTF_Z",
5579				     "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5580				$show_Z = 0;
5581			}
5582			# check for 0x<decimal>
5583			if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5584				ERROR("PRINTF_0XDECIMAL",
5585				      "Prefixing 0x with decimal output is defective\n" . $herecurr);
5586			}
5587		}
5588
5589# check for line continuations in quoted strings with odd counts of "
5590		if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5591			WARN("LINE_CONTINUATIONS",
5592			     "Avoid line continuations in quoted strings\n" . $herecurr);
5593		}
5594
5595# warn about #if 0
5596		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5597			WARN("IF_0",
5598			     "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5599		}
5600
5601# warn about #if 1
5602		if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5603			WARN("IF_1",
5604			     "Consider removing the #if 1 and its #endif\n" . $herecurr);
5605		}
5606
5607# check for needless "if (<foo>) fn(<foo>)" uses
5608		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5609			my $tested = quotemeta($1);
5610			my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5611			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5612				my $func = $1;
5613				if (WARN('NEEDLESS_IF',
5614					 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5615				    $fix) {
5616					my $do_fix = 1;
5617					my $leading_tabs = "";
5618					my $new_leading_tabs = "";
5619					if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5620						$leading_tabs = $1;
5621					} else {
5622						$do_fix = 0;
5623					}
5624					if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5625						$new_leading_tabs = $1;
5626						if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5627							$do_fix = 0;
5628						}
5629					} else {
5630						$do_fix = 0;
5631					}
5632					if ($do_fix) {
5633						fix_delete_line($fixlinenr - 1, $prevrawline);
5634						$fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5635					}
5636				}
5637			}
5638		}
5639
5640# check for unnecessary "Out of Memory" messages
5641		if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5642		    $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5643		    (defined $1 || defined $3) &&
5644		    $linenr > 3) {
5645			my $testval = $2;
5646			my $testline = $lines[$linenr - 3];
5647
5648			my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5649#			print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5650
5651			if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5652			    $s !~ /\b__GFP_NOWARN\b/ ) {
5653				WARN("OOM_MESSAGE",
5654				     "Possible unnecessary 'out of memory' message\n" . $hereprev);
5655			}
5656		}
5657
5658# check for logging functions with KERN_<LEVEL>
5659		if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5660		    $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5661			my $level = $1;
5662			if (WARN("UNNECESSARY_KERN_LEVEL",
5663				 "Possible unnecessary $level\n" . $herecurr) &&
5664			    $fix) {
5665				$fixed[$fixlinenr] =~ s/\s*$level\s*//;
5666			}
5667		}
5668
5669# check for logging continuations
5670		if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5671			WARN("LOGGING_CONTINUATION",
5672			     "Avoid logging continuation uses where feasible\n" . $herecurr);
5673		}
5674
5675# check for mask then right shift without a parentheses
5676		if ($perl_version_ok &&
5677		    $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5678		    $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5679			WARN("MASK_THEN_SHIFT",
5680			     "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5681		}
5682
5683# check for pointer comparisons to NULL
5684		if ($perl_version_ok) {
5685			while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5686				my $val = $1;
5687				my $equal = "!";
5688				$equal = "" if ($4 eq "!=");
5689				if (CHK("COMPARISON_TO_NULL",
5690					"Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5691					    $fix) {
5692					$fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5693				}
5694			}
5695		}
5696
5697# check for bad placement of section $InitAttribute (e.g.: __initdata)
5698		if ($line =~ /(\b$InitAttribute\b)/) {
5699			my $attr = $1;
5700			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5701				my $ptr = $1;
5702				my $var = $2;
5703				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5704				      ERROR("MISPLACED_INIT",
5705					    "$attr should be placed after $var\n" . $herecurr)) ||
5706				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5707				      WARN("MISPLACED_INIT",
5708					   "$attr should be placed after $var\n" . $herecurr))) &&
5709				    $fix) {
5710					$fixed[$fixlinenr] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e;
5711				}
5712			}
5713		}
5714
5715# check for $InitAttributeData (ie: __initdata) with const
5716		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5717			my $attr = $1;
5718			$attr =~ /($InitAttributePrefix)(.*)/;
5719			my $attr_prefix = $1;
5720			my $attr_type = $2;
5721			if (ERROR("INIT_ATTRIBUTE",
5722				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5723			    $fix) {
5724				$fixed[$fixlinenr] =~
5725				    s/$InitAttributeData/${attr_prefix}initconst/;
5726			}
5727		}
5728
5729# check for $InitAttributeConst (ie: __initconst) without const
5730		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5731			my $attr = $1;
5732			if (ERROR("INIT_ATTRIBUTE",
5733				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
5734			    $fix) {
5735				my $lead = $fixed[$fixlinenr] =~
5736				    /(^\+\s*(?:static\s+))/;
5737				$lead = rtrim($1);
5738				$lead = "$lead " if ($lead !~ /^\+$/);
5739				$lead = "${lead}const ";
5740				$fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5741			}
5742		}
5743
5744# check for __read_mostly with const non-pointer (should just be const)
5745		if ($line =~ /\b__read_mostly\b/ &&
5746		    $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5747			if (ERROR("CONST_READ_MOSTLY",
5748				  "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5749			    $fix) {
5750				$fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5751			}
5752		}
5753
5754# don't use __constant_<foo> functions outside of include/uapi/
5755		if ($realfile !~ m@^include/uapi/@ &&
5756		    $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5757			my $constant_func = $1;
5758			my $func = $constant_func;
5759			$func =~ s/^__constant_//;
5760			if (WARN("CONSTANT_CONVERSION",
5761				 "$constant_func should be $func\n" . $herecurr) &&
5762			    $fix) {
5763				$fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5764			}
5765		}
5766
5767# prefer usleep_range over udelay
5768		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5769			my $delay = $1;
5770			# ignore udelay's < 10, however
5771			if (! ($delay < 10) ) {
5772				CHK("USLEEP_RANGE",
5773				    "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5774			}
5775			if ($delay > 2000) {
5776				WARN("LONG_UDELAY",
5777				     "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5778			}
5779		}
5780
5781# warn about unexpectedly long msleep's
5782		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5783			if ($1 < 20) {
5784				WARN("MSLEEP",
5785				     "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5786			}
5787		}
5788
5789# check for comparisons of jiffies
5790		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5791			WARN("JIFFIES_COMPARISON",
5792			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5793		}
5794
5795# check for comparisons of get_jiffies_64()
5796		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5797			WARN("JIFFIES_COMPARISON",
5798			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5799		}
5800
5801# warn about #ifdefs in C files
5802#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5803#			print "#ifdef in C files should be avoided\n";
5804#			print "$herecurr";
5805#			$clean = 0;
5806#		}
5807
5808# warn about spacing in #ifdefs
5809		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5810			if (ERROR("SPACING",
5811				  "exactly one space required after that #$1\n" . $herecurr) &&
5812			    $fix) {
5813				$fixed[$fixlinenr] =~
5814				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5815			}
5816
5817		}
5818
5819# check for spinlock_t definitions without a comment.
5820		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5821		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5822			my $which = $1;
5823			if (!ctx_has_comment($first_line, $linenr)) {
5824				CHK("UNCOMMENTED_DEFINITION",
5825				    "$1 definition without comment\n" . $herecurr);
5826			}
5827		}
5828# check for memory barriers without a comment.
5829
5830		my $barriers = qr{
5831			mb|
5832			rmb|
5833			wmb|
5834			read_barrier_depends
5835		}x;
5836		my $barrier_stems = qr{
5837			mb__before_atomic|
5838			mb__after_atomic|
5839			store_release|
5840			load_acquire|
5841			store_mb|
5842			(?:$barriers)
5843		}x;
5844		my $all_barriers = qr{
5845			(?:$barriers)|
5846			smp_(?:$barrier_stems)|
5847			virt_(?:$barrier_stems)
5848		}x;
5849
5850		if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5851			if (!ctx_has_comment($first_line, $linenr)) {
5852				WARN("MEMORY_BARRIER",
5853				     "memory barrier without comment\n" . $herecurr);
5854			}
5855		}
5856
5857		my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5858
5859		if ($realfile !~ m@^include/asm-generic/@ &&
5860		    $realfile !~ m@/barrier\.h$@ &&
5861		    $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5862		    $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5863			WARN("MEMORY_BARRIER",
5864			     "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5865		}
5866
5867# check for waitqueue_active without a comment.
5868		if ($line =~ /\bwaitqueue_active\s*\(/) {
5869			if (!ctx_has_comment($first_line, $linenr)) {
5870				WARN("WAITQUEUE_ACTIVE",
5871				     "waitqueue_active without comment\n" . $herecurr);
5872			}
5873		}
5874
5875# check for smp_read_barrier_depends and read_barrier_depends
5876		if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5877			WARN("READ_BARRIER_DEPENDS",
5878			     "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5879		}
5880
5881# check of hardware specific defines
5882		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5883			CHK("ARCH_DEFINES",
5884			    "architecture specific defines should be avoided\n" .  $herecurr);
5885		}
5886
5887# check that the storage class is not after a type
5888		if ($line =~ /\b($Type)\s+($Storage)\b/) {
5889			WARN("STORAGE_CLASS",
5890			     "storage class '$2' should be located before type '$1'\n" . $herecurr);
5891		}
5892# Check that the storage class is at the beginning of a declaration
5893		if ($line =~ /\b$Storage\b/ &&
5894		    $line !~ /^.\s*$Storage/ &&
5895		    $line =~ /^.\s*(.+?)\$Storage\s/ &&
5896		    $1 !~ /[\,\)]\s*$/) {
5897			WARN("STORAGE_CLASS",
5898			     "storage class should be at the beginning of the declaration\n" . $herecurr);
5899		}
5900
5901# check the location of the inline attribute, that it is between
5902# storage class and type.
5903		if ($line =~ /\b$Type\s+$Inline\b/ ||
5904		    $line =~ /\b$Inline\s+$Storage\b/) {
5905			ERROR("INLINE_LOCATION",
5906			      "inline keyword should sit between storage class and type\n" . $herecurr);
5907		}
5908
5909# Check for __inline__ and __inline, prefer inline
5910		if ($realfile !~ m@\binclude/uapi/@ &&
5911		    $line =~ /\b(__inline__|__inline)\b/) {
5912			if (WARN("INLINE",
5913				 "plain inline is preferred over $1\n" . $herecurr) &&
5914			    $fix) {
5915				$fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5916
5917			}
5918		}
5919
5920# Check for __attribute__ packed, prefer __packed
5921		if ($realfile !~ m@\binclude/uapi/@ &&
5922		    $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5923			WARN("PREFER_PACKED",
5924			     "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5925		}
5926
5927# Check for __attribute__ aligned, prefer __aligned
5928		if ($realfile !~ m@\binclude/uapi/@ &&
5929		    $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5930			WARN("PREFER_ALIGNED",
5931			     "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5932		}
5933
5934# Check for __attribute__ section, prefer __section
5935		if ($realfile !~ m@\binclude/uapi/@ &&
5936		    $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
5937			my $old = substr($rawline, $-[1], $+[1] - $-[1]);
5938			my $new = substr($old, 1, -1);
5939			if (WARN("PREFER_SECTION",
5940				 "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
5941			    $fix) {
5942				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
5943			}
5944		}
5945
5946# Check for __attribute__ format(printf, prefer __printf
5947		if ($realfile !~ m@\binclude/uapi/@ &&
5948		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5949			if (WARN("PREFER_PRINTF",
5950				 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5951			    $fix) {
5952				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5953
5954			}
5955		}
5956
5957# Check for __attribute__ format(scanf, prefer __scanf
5958		if ($realfile !~ m@\binclude/uapi/@ &&
5959		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5960			if (WARN("PREFER_SCANF",
5961				 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5962			    $fix) {
5963				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5964			}
5965		}
5966
5967# Check for __attribute__ weak, or __weak declarations (may have link issues)
5968		if ($perl_version_ok &&
5969		    $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5970		    ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5971		     $line =~ /\b__weak\b/)) {
5972			ERROR("WEAK_DECLARATION",
5973			      "Using weak declarations can have unintended link defects\n" . $herecurr);
5974		}
5975
5976# check for c99 types like uint8_t used outside of uapi/ and tools/
5977		if (!$SOF &&
5978		    $realfile !~ m@\binclude/uapi/@ &&
5979		    $realfile !~ m@\btools/@ &&
5980		    $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5981			my $type = $1;
5982			if ($type =~ /\b($typeC99Typedefs)\b/) {
5983				$type = $1;
5984				my $kernel_type = 'u';
5985				$kernel_type = 's' if ($type =~ /^_*[si]/);
5986				$type =~ /(\d+)/;
5987				$kernel_type .= $1;
5988				if (CHK("PREFER_KERNEL_TYPES",
5989					"Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5990				    $fix) {
5991					$fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5992				}
5993			}
5994		}
5995
5996# check for cast of C90 native int or longer types constants
5997		if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5998			my $cast = $1;
5999			my $const = $2;
6000			if (WARN("TYPECAST_INT_CONSTANT",
6001				 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
6002			    $fix) {
6003				my $suffix = "";
6004				my $newconst = $const;
6005				$newconst =~ s/${Int_type}$//;
6006				$suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6007				if ($cast =~ /\blong\s+long\b/) {
6008					$suffix .= 'LL';
6009				} elsif ($cast =~ /\blong\b/) {
6010					$suffix .= 'L';
6011				}
6012				$fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6013			}
6014		}
6015
6016# check for sizeof(&)
6017		if ($line =~ /\bsizeof\s*\(\s*\&/) {
6018			WARN("SIZEOF_ADDRESS",
6019			     "sizeof(& should be avoided\n" . $herecurr);
6020		}
6021
6022# check for sizeof without parenthesis
6023		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6024			if (WARN("SIZEOF_PARENTHESIS",
6025				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6026			    $fix) {
6027				$fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6028			}
6029		}
6030
6031# check for struct spinlock declarations
6032		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6033			WARN("USE_SPINLOCK_T",
6034			     "struct spinlock should be spinlock_t\n" . $herecurr);
6035		}
6036
6037# check for seq_printf uses that could be seq_puts
6038		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6039			my $fmt = get_quoted_string($line, $rawline);
6040			$fmt =~ s/%%//g;
6041			if ($fmt !~ /%/) {
6042				if (WARN("PREFER_SEQ_PUTS",
6043					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6044				    $fix) {
6045					$fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6046				}
6047			}
6048		}
6049
6050# check for memcpy uses that should be memcpy_s
6051		if ($SOF && ($line =~ /memcpy\s*\(.*/)) {
6052			my $fmt = get_quoted_string($line, $rawline);
6053			$fmt =~ s/%%//g;
6054			if ($fmt !~ /%/) {
6055				if (WARN("PREFER_MEMCPY_S",
6056					 "Use safe version of memcpy - memcpy_s whenever possible\n" . $herecurr) &&
6057				    $fix) {
6058					$fixed[$fixlinenr] =~ s/memcpy\b/memcpy_s/;
6059				}
6060			}
6061		}
6062
6063# check for vsprintf extension %p<foo> misuses
6064		if ($perl_version_ok &&
6065		    defined $stat &&
6066		    $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6067		    $1 !~ /^_*volatile_*$/) {
6068			my $stat_real;
6069
6070			my $lc = $stat =~ tr@\n@@;
6071			$lc = $lc + $linenr;
6072		        for (my $count = $linenr; $count <= $lc; $count++) {
6073				my $specifier;
6074				my $extension;
6075				my $bad_specifier = "";
6076				my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6077				$fmt =~ s/%%//g;
6078
6079				while ($fmt =~ /(\%[\*\d\.]*p(\w))/g) {
6080					$specifier = $1;
6081					$extension = $2;
6082					if ($extension !~ /[SsBKRraEhMmIiUDdgVCbGNOxt]/) {
6083						$bad_specifier = $specifier;
6084						last;
6085					}
6086					if ($extension eq "x" && !defined($stat_real)) {
6087						if (!defined($stat_real)) {
6088							$stat_real = get_stat_real($linenr, $lc);
6089						}
6090						WARN("VSPRINTF_SPECIFIER_PX",
6091						     "Using vsprintf specifier '\%px' potentially exposes the kernel memory layout, if you don't really need the address please consider using '\%p'.\n" . "$here\n$stat_real\n");
6092					}
6093				}
6094				if ($bad_specifier ne "") {
6095					my $stat_real = get_stat_real($linenr, $lc);
6096					my $ext_type = "Invalid";
6097					my $use = "";
6098					if ($bad_specifier =~ /p[Ff]/) {
6099						$ext_type = "Deprecated";
6100						$use = " - use %pS instead";
6101						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6102					}
6103
6104					WARN("VSPRINTF_POINTER_EXTENSION",
6105					     "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6106				}
6107			}
6108		}
6109
6110# Check for misused memsets
6111		if ($perl_version_ok &&
6112		    defined $stat &&
6113		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6114
6115			my $ms_addr = $2;
6116			my $ms_val = $7;
6117			my $ms_size = $12;
6118
6119			if ($ms_size =~ /^(0x|)0$/i) {
6120				ERROR("MEMSET",
6121				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6122			} elsif ($ms_size =~ /^(0x|)1$/i) {
6123				WARN("MEMSET",
6124				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6125			}
6126		}
6127
6128# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6129#		if ($perl_version_ok &&
6130#		    defined $stat &&
6131#		    $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6132#			if (WARN("PREFER_ETHER_ADDR_COPY",
6133#				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6134#			    $fix) {
6135#				$fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6136#			}
6137#		}
6138
6139# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6140#		if ($perl_version_ok &&
6141#		    defined $stat &&
6142#		    $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6143#			WARN("PREFER_ETHER_ADDR_EQUAL",
6144#			     "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6145#		}
6146
6147# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6148# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6149#		if ($perl_version_ok &&
6150#		    defined $stat &&
6151#		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6152#
6153#			my $ms_val = $7;
6154#
6155#			if ($ms_val =~ /^(?:0x|)0+$/i) {
6156#				if (WARN("PREFER_ETH_ZERO_ADDR",
6157#					 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6158#				    $fix) {
6159#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6160#				}
6161#			} elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6162#				if (WARN("PREFER_ETH_BROADCAST_ADDR",
6163#					 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6164#				    $fix) {
6165#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6166#				}
6167#			}
6168#		}
6169
6170# typecasts on min/max could be min_t/max_t
6171		if ($perl_version_ok &&
6172		    defined $stat &&
6173		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6174			if (defined $2 || defined $7) {
6175				my $call = $1;
6176				my $cast1 = deparenthesize($2);
6177				my $arg1 = $3;
6178				my $cast2 = deparenthesize($7);
6179				my $arg2 = $8;
6180				my $cast;
6181
6182				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6183					$cast = "$cast1 or $cast2";
6184				} elsif ($cast1 ne "") {
6185					$cast = $cast1;
6186				} else {
6187					$cast = $cast2;
6188				}
6189				WARN("MINMAX",
6190				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6191			}
6192		}
6193
6194# check usleep_range arguments
6195		if ($perl_version_ok &&
6196		    defined $stat &&
6197		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6198			my $min = $1;
6199			my $max = $7;
6200			if ($min eq $max) {
6201				WARN("USLEEP_RANGE",
6202				     "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6203			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6204				 $min > $max) {
6205				WARN("USLEEP_RANGE",
6206				     "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6207			}
6208		}
6209
6210# check for naked sscanf
6211		if ($perl_version_ok &&
6212		    defined $stat &&
6213		    $line =~ /\bsscanf\b/ &&
6214		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6215		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6216		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6217			my $lc = $stat =~ tr@\n@@;
6218			$lc = $lc + $linenr;
6219			my $stat_real = get_stat_real($linenr, $lc);
6220			WARN("NAKED_SSCANF",
6221			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6222		}
6223
6224# check for simple sscanf that should be kstrto<foo>
6225		if ($perl_version_ok &&
6226		    defined $stat &&
6227		    $line =~ /\bsscanf\b/) {
6228			my $lc = $stat =~ tr@\n@@;
6229			$lc = $lc + $linenr;
6230			my $stat_real = get_stat_real($linenr, $lc);
6231			if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6232				my $format = $6;
6233				my $count = $format =~ tr@%@%@;
6234				if ($count == 1 &&
6235				    $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6236					WARN("SSCANF_TO_KSTRTO",
6237					     "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6238				}
6239			}
6240		}
6241
6242# check for new externs in .h files.
6243		if ($realfile =~ /\.h$/ &&
6244		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6245			if (CHK("AVOID_EXTERNS",
6246				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
6247			    $fix) {
6248				$fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6249			}
6250		}
6251
6252# check for new externs in .c files.
6253		if ($realfile =~ /\.c$/ && defined $stat &&
6254		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6255		{
6256			my $function_name = $1;
6257			my $paren_space = $2;
6258
6259			my $s = $stat;
6260			if (defined $cond) {
6261				substr($s, 0, length($cond), '');
6262			}
6263			if ($s =~ /^\s*;/ &&
6264			    $function_name ne 'uninitialized_var')
6265			{
6266				WARN("AVOID_EXTERNS",
6267				     "externs should be avoided in .c files\n" .  $herecurr);
6268			}
6269
6270			if ($paren_space =~ /\n/) {
6271				WARN("FUNCTION_ARGUMENTS",
6272				     "arguments for function declarations should follow identifier\n" . $herecurr);
6273			}
6274
6275		} elsif ($realfile =~ /\.c$/ && defined $stat &&
6276		    $stat =~ /^.\s*extern\s+/)
6277		{
6278			WARN("AVOID_EXTERNS",
6279			     "externs should be avoided in .c files\n" .  $herecurr);
6280		}
6281
6282# check for function declarations that have arguments without identifier names
6283		if (defined $stat &&
6284		    $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6285		    $1 ne "void") {
6286			my $args = trim($1);
6287			while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6288				my $arg = trim($1);
6289				if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6290					WARN("FUNCTION_ARGUMENTS",
6291					     "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6292				}
6293			}
6294		}
6295
6296# check for function definitions
6297		if ($perl_version_ok &&
6298		    defined $stat &&
6299		    $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6300			$context_function = $1;
6301
6302# check for multiline function definition with misplaced open brace
6303			my $ok = 0;
6304			my $cnt = statement_rawlines($stat);
6305			my $herectx = $here . "\n";
6306			for (my $n = 0; $n < $cnt; $n++) {
6307				my $rl = raw_line($linenr, $n);
6308				$herectx .=  $rl . "\n";
6309				$ok = 1 if ($rl =~ /^[ \+]\{/);
6310				$ok = 1 if ($rl =~ /\{/ && $n == 0);
6311				last if $rl =~ /^[ \+].*\{/;
6312			}
6313			if (!$ok) {
6314				ERROR("OPEN_BRACE",
6315				      "open brace '{' following function definitions go on the next line\n" . $herectx);
6316			}
6317		}
6318
6319# checks for new __setup's
6320		if ($rawline =~ /\b__setup\("([^"]*)"/) {
6321			my $name = $1;
6322
6323			if (!grep(/$name/, @setup_docs)) {
6324				CHK("UNDOCUMENTED_SETUP",
6325				    "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6326			}
6327		}
6328
6329# check for pointless casting of alloc functions
6330		if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6331			WARN("UNNECESSARY_CASTS",
6332			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6333		}
6334
6335# alloc style
6336# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6337		if ($perl_version_ok &&
6338		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6339			CHK("ALLOC_SIZEOF_STRUCT",
6340			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6341		}
6342
6343# check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6344		if ($perl_version_ok &&
6345		    defined $stat &&
6346		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6347			my $oldfunc = $3;
6348			my $a1 = $4;
6349			my $a2 = $10;
6350			my $newfunc = "kmalloc_array";
6351			$newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6352			my $r1 = $a1;
6353			my $r2 = $a2;
6354			if ($a1 =~ /^sizeof\s*\S/) {
6355				$r1 = $a2;
6356				$r2 = $a1;
6357			}
6358			if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6359			    !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6360				my $cnt = statement_rawlines($stat);
6361				my $herectx = get_stat_here($linenr, $cnt, $here);
6362
6363				if (WARN("ALLOC_WITH_MULTIPLY",
6364					 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6365				    $cnt == 1 &&
6366				    $fix) {
6367					$fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)/$1 . ' = ' . "$newfunc(" . trim($r1) . ', ' . trim($r2)/e;
6368				}
6369			}
6370		}
6371
6372# check for krealloc arg reuse
6373		if ($perl_version_ok &&
6374		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6375		    $1 eq $3) {
6376			WARN("KREALLOC_ARG_REUSE",
6377			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6378		}
6379
6380# check for alloc argument mismatch
6381		if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6382			WARN("ALLOC_ARRAY_ARGS",
6383			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6384		}
6385
6386# check for multiple semicolons
6387		if ($line =~ /;\s*;\s*$/) {
6388			if (WARN("ONE_SEMICOLON",
6389				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6390			    $fix) {
6391				$fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6392			}
6393		}
6394
6395# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6396		if ($realfile !~ m@^include/uapi/@ &&
6397		    $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6398			my $ull = "";
6399			$ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6400			if (CHK("BIT_MACRO",
6401				"Prefer using the BIT$ull macro\n" . $herecurr) &&
6402			    $fix) {
6403				$fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6404			}
6405		}
6406
6407# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6408		if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6409			my $config = $1;
6410			if (WARN("PREFER_IS_ENABLED",
6411				 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6412			    $fix) {
6413				$fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6414			}
6415		}
6416
6417# check for case / default statements not preceded by break/fallthrough/switch
6418		if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6419			my $has_break = 0;
6420			my $has_statement = 0;
6421			my $count = 0;
6422			my $prevline = $linenr;
6423			while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6424				$prevline--;
6425				my $rline = $rawlines[$prevline - 1];
6426				my $fline = $lines[$prevline - 1];
6427				last if ($fline =~ /^\@\@/);
6428				next if ($fline =~ /^\-/);
6429				next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6430				$has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6431				next if ($fline =~ /^.[\s$;]*$/);
6432				$has_statement = 1;
6433				$count++;
6434				$has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6435			}
6436			if (!$has_break && $has_statement) {
6437				WARN("MISSING_BREAK",
6438				     "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6439			}
6440		}
6441
6442# check for switch/default statements without a break;
6443		if ($perl_version_ok &&
6444		    defined $stat &&
6445		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6446			my $cnt = statement_rawlines($stat);
6447			my $herectx = get_stat_here($linenr, $cnt, $here);
6448
6449			WARN("DEFAULT_NO_BREAK",
6450			     "switch default: should use break\n" . $herectx);
6451		}
6452
6453# check for gcc specific __FUNCTION__
6454		if ($line =~ /\b__FUNCTION__\b/) {
6455			if (WARN("USE_FUNC",
6456				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
6457			    $fix) {
6458				$fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6459			}
6460		}
6461
6462# check for uses of __DATE__, __TIME__, __TIMESTAMP__
6463		while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6464			ERROR("DATE_TIME",
6465			      "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6466		}
6467
6468# check for use of yield()
6469		if ($line =~ /\byield\s*\(\s*\)/) {
6470			WARN("YIELD",
6471			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
6472		}
6473
6474# check for comparisons against true and false
6475		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6476			my $lead = $1;
6477			my $arg = $2;
6478			my $test = $3;
6479			my $otype = $4;
6480			my $trail = $5;
6481			my $op = "!";
6482
6483			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6484
6485			my $type = lc($otype);
6486			if ($type =~ /^(?:true|false)$/) {
6487				if (("$test" eq "==" && "$type" eq "true") ||
6488				    ("$test" eq "!=" && "$type" eq "false")) {
6489					$op = "";
6490				}
6491
6492				CHK("BOOL_COMPARISON",
6493				    "Using comparison to $otype is error prone\n" . $herecurr);
6494
6495## maybe suggesting a correct construct would better
6496##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6497
6498			}
6499		}
6500
6501# check for semaphores initialized locked
6502		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6503			WARN("CONSIDER_COMPLETION",
6504			     "consider using a completion\n" . $herecurr);
6505		}
6506
6507# recommend kstrto* over simple_strto* and strict_strto*
6508		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6509			WARN("CONSIDER_KSTRTO",
6510			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
6511		}
6512
6513# check for __initcall(), use device_initcall() explicitly or more appropriate function please
6514		if ($line =~ /^.\s*__initcall\s*\(/) {
6515			WARN("USE_DEVICE_INITCALL",
6516			     "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6517		}
6518
6519# check for spin_is_locked(), suggest lockdep instead
6520		if ($line =~ /\bspin_is_locked\(/) {
6521			WARN("USE_LOCKDEP",
6522			     "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6523		}
6524
6525# check for deprecated apis
6526		if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6527			my $deprecated_api = $1;
6528			my $new_api = $deprecated_apis{$deprecated_api};
6529			WARN("DEPRECATED_API",
6530			     "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6531		}
6532
6533# check for various structs that are normally const (ops, kgdb, device_tree)
6534# and avoid what seem like struct definitions 'struct foo {'
6535		if ($line !~ /\bconst\b/ &&
6536		    $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6537			WARN("CONST_STRUCT",
6538			     "struct $1 should normally be const\n" . $herecurr);
6539		}
6540
6541# use of NR_CPUS is usually wrong
6542# ignore definitions of NR_CPUS and usage to define arrays as likely right
6543		if ($line =~ /\bNR_CPUS\b/ &&
6544		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6545		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6546		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6547		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6548		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6549		{
6550			WARN("NR_CPUS",
6551			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6552		}
6553
6554# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6555		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6556			ERROR("DEFINE_ARCH_HAS",
6557			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6558		}
6559
6560# likely/unlikely comparisons similar to "(likely(foo) > 0)"
6561		if ($perl_version_ok &&
6562		    $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6563			WARN("LIKELY_MISUSE",
6564			     "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6565		}
6566
6567# nested likely/unlikely calls
6568		if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6569			WARN("LIKELY_MISUSE",
6570			     "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6571		}
6572
6573# whine mightly about in_atomic
6574		if ($line =~ /\bin_atomic\s*\(/) {
6575			if ($realfile =~ m@^drivers/@) {
6576				ERROR("IN_ATOMIC",
6577				      "do not use in_atomic in drivers\n" . $herecurr);
6578			} elsif ($realfile !~ m@^kernel/@) {
6579				WARN("IN_ATOMIC",
6580				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6581			}
6582		}
6583
6584# check for mutex_trylock_recursive usage
6585		if ($line =~ /mutex_trylock_recursive/) {
6586			ERROR("LOCKING",
6587			      "recursive locking is bad, do not use this ever.\n" . $herecurr);
6588		}
6589
6590# check for lockdep_set_novalidate_class
6591		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6592		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
6593			if ($realfile !~ m@^kernel/lockdep@ &&
6594			    $realfile !~ m@^include/linux/lockdep@ &&
6595			    $realfile !~ m@^drivers/base/core@) {
6596				ERROR("LOCKDEP",
6597				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6598			}
6599		}
6600
6601		if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6602		    $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6603			WARN("EXPORTED_WORLD_WRITABLE",
6604			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6605		}
6606
6607# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6608# and whether or not function naming is typical and if
6609# DEVICE_ATTR permissions uses are unusual too
6610		if ($perl_version_ok &&
6611		    defined $stat &&
6612		    $stat =~ /\bDEVICE_ATTR\s*\(\s*(\w+)\s*,\s*\(?\s*(\s*(?:${multi_mode_perms_string_search}|0[0-7]{3,3})\s*)\s*\)?\s*,\s*(\w+)\s*,\s*(\w+)\s*\)/) {
6613			my $var = $1;
6614			my $perms = $2;
6615			my $show = $3;
6616			my $store = $4;
6617			my $octal_perms = perms_to_octal($perms);
6618			if ($show =~ /^${var}_show$/ &&
6619			    $store =~ /^${var}_store$/ &&
6620			    $octal_perms eq "0644") {
6621				if (WARN("DEVICE_ATTR_RW",
6622					 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6623				    $fix) {
6624					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6625				}
6626			} elsif ($show =~ /^${var}_show$/ &&
6627				 $store =~ /^NULL$/ &&
6628				 $octal_perms eq "0444") {
6629				if (WARN("DEVICE_ATTR_RO",
6630					 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6631				    $fix) {
6632					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6633				}
6634			} elsif ($show =~ /^NULL$/ &&
6635				 $store =~ /^${var}_store$/ &&
6636				 $octal_perms eq "0200") {
6637				if (WARN("DEVICE_ATTR_WO",
6638					 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6639				    $fix) {
6640					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6641				}
6642			} elsif ($octal_perms eq "0644" ||
6643				 $octal_perms eq "0444" ||
6644				 $octal_perms eq "0200") {
6645				my $newshow = "$show";
6646				$newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6647				my $newstore = $store;
6648				$newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6649				my $rename = "";
6650				if ($show ne $newshow) {
6651					$rename .= " '$show' to '$newshow'";
6652				}
6653				if ($store ne $newstore) {
6654					$rename .= " '$store' to '$newstore'";
6655				}
6656				WARN("DEVICE_ATTR_FUNCTIONS",
6657				     "Consider renaming function(s)$rename\n" . $herecurr);
6658			} else {
6659				WARN("DEVICE_ATTR_PERMS",
6660				     "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6661			}
6662		}
6663
6664# Mode permission misuses where it seems decimal should be octal
6665# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6666# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6667#   specific definition of not visible in sysfs.
6668# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6669#   use the default permissions
6670		if ($perl_version_ok &&
6671		    defined $stat &&
6672		    $line =~ /$mode_perms_search/) {
6673			foreach my $entry (@mode_permission_funcs) {
6674				my $func = $entry->[0];
6675				my $arg_pos = $entry->[1];
6676
6677				my $lc = $stat =~ tr@\n@@;
6678				$lc = $lc + $linenr;
6679				my $stat_real = get_stat_real($linenr, $lc);
6680
6681				my $skip_args = "";
6682				if ($arg_pos > 1) {
6683					$arg_pos--;
6684					$skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6685				}
6686				my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6687				if ($stat =~ /$test/) {
6688					my $val = $1;
6689					$val = $6 if ($skip_args ne "");
6690					if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6691					    (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6692					     ($val =~ /^$Octal$/ && length($val) ne 4))) {
6693						ERROR("NON_OCTAL_PERMISSIONS",
6694						      "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6695					}
6696					if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6697						ERROR("EXPORTED_WORLD_WRITABLE",
6698						      "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6699					}
6700				}
6701			}
6702		}
6703
6704# check for uses of S_<PERMS> that could be octal for readability
6705		while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6706			my $oval = $1;
6707			my $octal = perms_to_octal($oval);
6708			if (WARN("SYMBOLIC_PERMS",
6709				 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6710			    $fix) {
6711				$fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6712			}
6713		}
6714
6715# validate content of MODULE_LICENSE against list from include/linux/module.h
6716		if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6717			my $extracted_string = get_quoted_string($line, $rawline);
6718			my $valid_licenses = qr{
6719						GPL|
6720						GPL\ v2|
6721						GPL\ and\ additional\ rights|
6722						Dual\ BSD/GPL|
6723						Dual\ MIT/GPL|
6724						Dual\ MPL/GPL|
6725						Proprietary
6726					}x;
6727			if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6728				WARN("MODULE_LICENSE",
6729				     "unknown module license " . $extracted_string . "\n" . $herecurr);
6730			}
6731		}
6732
6733# check for sysctl duplicate constants
6734		if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6735			WARN("DUPLICATED_SYSCTL_CONST",
6736				"duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6737		}
6738	}
6739
6740	# If we have no input at all, then there is nothing to report on
6741	# so just keep quiet.
6742	if ($#rawlines == -1) {
6743		exit(0);
6744	}
6745
6746	# In mailback mode only produce a report in the negative, for
6747	# things that appear to be patches.
6748	if ($mailback && ($clean == 1 || !$is_patch)) {
6749		exit(0);
6750	}
6751
6752	# This is not a patch, and we are are in 'no-patch' mode so
6753	# just keep quiet.
6754	if (!$chk_patch && !$is_patch) {
6755		exit(0);
6756	}
6757
6758	if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6759		ERROR("NOT_UNIFIED_DIFF",
6760		      "Does not appear to be a unified-diff format patch\n");
6761	}
6762	if ($is_patch && $has_commit_log && $chk_signoff) {
6763		if ($signoff == 0) {
6764			ERROR("MISSING_SIGN_OFF",
6765			      "Missing Signed-off-by: line(s)\n");
6766		} elsif (!$authorsignoff) {
6767			WARN("NO_AUTHOR_SIGN_OFF",
6768			     "Missing Signed-off-by: line by nominal patch author '$author'\n");
6769		}
6770	}
6771
6772	print report_dump();
6773	if ($summary && !($clean == 1 && $quiet == 1)) {
6774		print "$filename " if ($summary_file);
6775		print "total: $cnt_error errors, $cnt_warn warnings, " .
6776			(($check)? "$cnt_chk checks, " : "") .
6777			"$cnt_lines lines checked\n";
6778	}
6779
6780	if ($quiet == 0) {
6781		# If there were any defects found and not already fixing them
6782		if (!$clean and !$fix) {
6783			print << "EOM"
6784
6785NOTE: For some of the reported defects, checkpatch may be able to
6786      mechanically convert to the typical style using --fix or --fix-inplace.
6787EOM
6788		}
6789		# If there were whitespace errors which cleanpatch can fix
6790		# then suggest that.
6791		if ($rpt_cleaners) {
6792			$rpt_cleaners = 0;
6793			print << "EOM"
6794
6795NOTE: Whitespace errors detected.
6796      You may wish to use scripts/cleanpatch or scripts/cleanfile
6797EOM
6798		}
6799	}
6800
6801	if ($clean == 0 && $fix &&
6802	    ("@rawlines" ne "@fixed" ||
6803	     $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6804		my $newfile = $filename;
6805		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6806		my $linecount = 0;
6807		my $f;
6808
6809		@fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6810
6811		open($f, '>', $newfile)
6812		    or die "$P: Can't open $newfile for write\n";
6813		foreach my $fixed_line (@fixed) {
6814			$linecount++;
6815			if ($file) {
6816				if ($linecount > 3) {
6817					$fixed_line =~ s/^\+//;
6818					print $f $fixed_line . "\n";
6819				}
6820			} else {
6821				print $f $fixed_line . "\n";
6822			}
6823		}
6824		close($f);
6825
6826		if (!$quiet) {
6827			print << "EOM";
6828
6829Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6830
6831Do _NOT_ trust the results written to this file.
6832Do _NOT_ submit these changes without inspecting them for correctness.
6833
6834This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6835No warranties, expressed or implied...
6836EOM
6837		}
6838	}
6839
6840	if ($quiet == 0) {
6841		print "\n";
6842		if ($clean == 1) {
6843			print "$vname has no obvious style problems and is ready for submission.\n";
6844		} else {
6845			print "$vname has style problems, please review.\n";
6846		}
6847	}
6848	return $clean;
6849}
6850