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