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