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