xref: /linux/scripts/checkpatch.pl (revision 4eb7ae7a301d3586c3351e81d5c3cfe2304a1a6a)
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 =~ /\bpr_warning\s*\(/) {
4129			if (WARN("PREFER_PR_LEVEL",
4130				 "Prefer pr_warn(... to pr_warning(...\n" . $herecurr) &&
4131			    $fix) {
4132				$fixed[$fixlinenr] =~
4133				    s/\bpr_warning\b/pr_warn/;
4134			}
4135		}
4136
4137		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4138			my $orig = $1;
4139			my $level = lc($orig);
4140			$level = "warn" if ($level eq "warning");
4141			$level = "dbg" if ($level eq "debug");
4142			WARN("PREFER_DEV_LEVEL",
4143			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4144		}
4145
4146# ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4147# number of false positives, but assembly files are not checked, so at
4148# least the arch entry code will not trigger this warning.
4149		if ($line =~ /\bENOSYS\b/) {
4150			WARN("ENOSYS",
4151			     "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4152		}
4153
4154# function brace can't be on same line, except for #defines of do while,
4155# or if closed on same line
4156		if ($perl_version_ok &&
4157		    $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4158		    $sline !~ /\#\s*define\b.*do\s*\{/ &&
4159		    $sline !~ /}/) {
4160			if (ERROR("OPEN_BRACE",
4161				  "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4162			    $fix) {
4163				fix_delete_line($fixlinenr, $rawline);
4164				my $fixed_line = $rawline;
4165				$fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*){(.*)$/;
4166				my $line1 = $1;
4167				my $line2 = $2;
4168				fix_insert_line($fixlinenr, ltrim($line1));
4169				fix_insert_line($fixlinenr, "\+{");
4170				if ($line2 !~ /^\s*$/) {
4171					fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4172				}
4173			}
4174		}
4175
4176# open braces for enum, union and struct go on the same line.
4177		if ($line =~ /^.\s*{/ &&
4178		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4179			if (ERROR("OPEN_BRACE",
4180				  "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4181			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4182				fix_delete_line($fixlinenr - 1, $prevrawline);
4183				fix_delete_line($fixlinenr, $rawline);
4184				my $fixedline = rtrim($prevrawline) . " {";
4185				fix_insert_line($fixlinenr, $fixedline);
4186				$fixedline = $rawline;
4187				$fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4188				if ($fixedline !~ /^\+\s*$/) {
4189					fix_insert_line($fixlinenr, $fixedline);
4190				}
4191			}
4192		}
4193
4194# missing space after union, struct or enum definition
4195		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4196			if (WARN("SPACING",
4197				 "missing space after $1 definition\n" . $herecurr) &&
4198			    $fix) {
4199				$fixed[$fixlinenr] =~
4200				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4201			}
4202		}
4203
4204# Function pointer declarations
4205# check spacing between type, funcptr, and args
4206# canonical declaration is "type (*funcptr)(args...)"
4207		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4208			my $declare = $1;
4209			my $pre_pointer_space = $2;
4210			my $post_pointer_space = $3;
4211			my $funcname = $4;
4212			my $post_funcname_space = $5;
4213			my $pre_args_space = $6;
4214
4215# the $Declare variable will capture all spaces after the type
4216# so check it for a missing trailing missing space but pointer return types
4217# don't need a space so don't warn for those.
4218			my $post_declare_space = "";
4219			if ($declare =~ /(\s+)$/) {
4220				$post_declare_space = $1;
4221				$declare = rtrim($declare);
4222			}
4223			if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
4224				WARN("SPACING",
4225				     "missing space after return type\n" . $herecurr);
4226				$post_declare_space = " ";
4227			}
4228
4229# unnecessary space "type  (*funcptr)(args...)"
4230# This test is not currently implemented because these declarations are
4231# equivalent to
4232#	int  foo(int bar, ...)
4233# and this is form shouldn't/doesn't generate a checkpatch warning.
4234#
4235#			elsif ($declare =~ /\s{2,}$/) {
4236#				WARN("SPACING",
4237#				     "Multiple spaces after return type\n" . $herecurr);
4238#			}
4239
4240# unnecessary space "type ( *funcptr)(args...)"
4241			if (defined $pre_pointer_space &&
4242			    $pre_pointer_space =~ /^\s/) {
4243				WARN("SPACING",
4244				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
4245			}
4246
4247# unnecessary space "type (* funcptr)(args...)"
4248			if (defined $post_pointer_space &&
4249			    $post_pointer_space =~ /^\s/) {
4250				WARN("SPACING",
4251				     "Unnecessary space before function pointer name\n" . $herecurr);
4252			}
4253
4254# unnecessary space "type (*funcptr )(args...)"
4255			if (defined $post_funcname_space &&
4256			    $post_funcname_space =~ /^\s/) {
4257				WARN("SPACING",
4258				     "Unnecessary space after function pointer name\n" . $herecurr);
4259			}
4260
4261# unnecessary space "type (*funcptr) (args...)"
4262			if (defined $pre_args_space &&
4263			    $pre_args_space =~ /^\s/) {
4264				WARN("SPACING",
4265				     "Unnecessary space before function pointer arguments\n" . $herecurr);
4266			}
4267
4268			if (show_type("SPACING") && $fix) {
4269				$fixed[$fixlinenr] =~
4270				    s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
4271			}
4272		}
4273
4274# check for spacing round square brackets; allowed:
4275#  1. with a type on the left -- int [] a;
4276#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
4277#  3. inside a curly brace -- = { [0...10] = 5 }
4278		while ($line =~ /(.*?\s)\[/g) {
4279			my ($where, $prefix) = ($-[1], $1);
4280			if ($prefix !~ /$Type\s+$/ &&
4281			    ($where != 0 || $prefix !~ /^.\s+$/) &&
4282			    $prefix !~ /[{,:]\s+$/) {
4283				if (ERROR("BRACKET_SPACE",
4284					  "space prohibited before open square bracket '['\n" . $herecurr) &&
4285				    $fix) {
4286				    $fixed[$fixlinenr] =~
4287					s/^(\+.*?)\s+\[/$1\[/;
4288				}
4289			}
4290		}
4291
4292# check for spaces between functions and their parentheses.
4293		while ($line =~ /($Ident)\s+\(/g) {
4294			my $name = $1;
4295			my $ctx_before = substr($line, 0, $-[1]);
4296			my $ctx = "$ctx_before$name";
4297
4298			# Ignore those directives where spaces _are_ permitted.
4299			if ($name =~ /^(?:
4300				if|for|while|switch|return|case|
4301				volatile|__volatile__|
4302				__attribute__|format|__extension__|
4303				asm|__asm__)$/x)
4304			{
4305			# cpp #define statements have non-optional spaces, ie
4306			# if there is a space between the name and the open
4307			# parenthesis it is simply not a parameter group.
4308			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
4309
4310			# cpp #elif statement condition may start with a (
4311			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
4312
4313			# If this whole things ends with a type its most
4314			# likely a typedef for a function.
4315			} elsif ($ctx =~ /$Type$/) {
4316
4317			} else {
4318				if (WARN("SPACING",
4319					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
4320					     $fix) {
4321					$fixed[$fixlinenr] =~
4322					    s/\b$name\s+\(/$name\(/;
4323				}
4324			}
4325		}
4326
4327# Check operator spacing.
4328		if (!($line=~/\#\s*include/)) {
4329			my $fixed_line = "";
4330			my $line_fixed = 0;
4331
4332			my $ops = qr{
4333				<<=|>>=|<=|>=|==|!=|
4334				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
4335				=>|->|<<|>>|<|>|=|!|~|
4336				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
4337				\?:|\?|:
4338			}x;
4339			my @elements = split(/($ops|;)/, $opline);
4340
4341##			print("element count: <" . $#elements . ">\n");
4342##			foreach my $el (@elements) {
4343##				print("el: <$el>\n");
4344##			}
4345
4346			my @fix_elements = ();
4347			my $off = 0;
4348
4349			foreach my $el (@elements) {
4350				push(@fix_elements, substr($rawline, $off, length($el)));
4351				$off += length($el);
4352			}
4353
4354			$off = 0;
4355
4356			my $blank = copy_spacing($opline);
4357			my $last_after = -1;
4358
4359			for (my $n = 0; $n < $#elements; $n += 2) {
4360
4361				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
4362
4363##				print("n: <$n> good: <$good>\n");
4364
4365				$off += length($elements[$n]);
4366
4367				# Pick up the preceding and succeeding characters.
4368				my $ca = substr($opline, 0, $off);
4369				my $cc = '';
4370				if (length($opline) >= ($off + length($elements[$n + 1]))) {
4371					$cc = substr($opline, $off + length($elements[$n + 1]));
4372				}
4373				my $cb = "$ca$;$cc";
4374
4375				my $a = '';
4376				$a = 'V' if ($elements[$n] ne '');
4377				$a = 'W' if ($elements[$n] =~ /\s$/);
4378				$a = 'C' if ($elements[$n] =~ /$;$/);
4379				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
4380				$a = 'O' if ($elements[$n] eq '');
4381				$a = 'E' if ($ca =~ /^\s*$/);
4382
4383				my $op = $elements[$n + 1];
4384
4385				my $c = '';
4386				if (defined $elements[$n + 2]) {
4387					$c = 'V' if ($elements[$n + 2] ne '');
4388					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
4389					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
4390					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
4391					$c = 'O' if ($elements[$n + 2] eq '');
4392					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
4393				} else {
4394					$c = 'E';
4395				}
4396
4397				my $ctx = "${a}x${c}";
4398
4399				my $at = "(ctx:$ctx)";
4400
4401				my $ptr = substr($blank, 0, $off) . "^";
4402				my $hereptr = "$hereline$ptr\n";
4403
4404				# Pull out the value of this operator.
4405				my $op_type = substr($curr_values, $off + 1, 1);
4406
4407				# Get the full operator variant.
4408				my $opv = $op . substr($curr_vars, $off, 1);
4409
4410				# Ignore operators passed as parameters.
4411				if ($op_type ne 'V' &&
4412				    $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
4413
4414#				# Ignore comments
4415#				} elsif ($op =~ /^$;+$/) {
4416
4417				# ; should have either the end of line or a space or \ after it
4418				} elsif ($op eq ';') {
4419					if ($ctx !~ /.x[WEBC]/ &&
4420					    $cc !~ /^\\/ && $cc !~ /^;/) {
4421						if (ERROR("SPACING",
4422							  "space required after that '$op' $at\n" . $hereptr)) {
4423							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4424							$line_fixed = 1;
4425						}
4426					}
4427
4428				# // is a comment
4429				} elsif ($op eq '//') {
4430
4431				#   :   when part of a bitfield
4432				} elsif ($opv eq ':B') {
4433					# skip the bitfield test for now
4434
4435				# No spaces for:
4436				#   ->
4437				} elsif ($op eq '->') {
4438					if ($ctx =~ /Wx.|.xW/) {
4439						if (ERROR("SPACING",
4440							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
4441							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4442							if (defined $fix_elements[$n + 2]) {
4443								$fix_elements[$n + 2] =~ s/^\s+//;
4444							}
4445							$line_fixed = 1;
4446						}
4447					}
4448
4449				# , must not have a space before and must have a space on the right.
4450				} elsif ($op eq ',') {
4451					my $rtrim_before = 0;
4452					my $space_after = 0;
4453					if ($ctx =~ /Wx./) {
4454						if (ERROR("SPACING",
4455							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4456							$line_fixed = 1;
4457							$rtrim_before = 1;
4458						}
4459					}
4460					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
4461						if (ERROR("SPACING",
4462							  "space required after that '$op' $at\n" . $hereptr)) {
4463							$line_fixed = 1;
4464							$last_after = $n;
4465							$space_after = 1;
4466						}
4467					}
4468					if ($rtrim_before || $space_after) {
4469						if ($rtrim_before) {
4470							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4471						} else {
4472							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4473						}
4474						if ($space_after) {
4475							$good .= " ";
4476						}
4477					}
4478
4479				# '*' as part of a type definition -- reported already.
4480				} elsif ($opv eq '*_') {
4481					#warn "'*' is part of type\n";
4482
4483				# unary operators should have a space before and
4484				# none after.  May be left adjacent to another
4485				# unary operator, or a cast
4486				} elsif ($op eq '!' || $op eq '~' ||
4487					 $opv eq '*U' || $opv eq '-U' ||
4488					 $opv eq '&U' || $opv eq '&&U') {
4489					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
4490						if (ERROR("SPACING",
4491							  "space required before that '$op' $at\n" . $hereptr)) {
4492							if ($n != $last_after + 2) {
4493								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
4494								$line_fixed = 1;
4495							}
4496						}
4497					}
4498					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
4499						# A unary '*' may be const
4500
4501					} elsif ($ctx =~ /.xW/) {
4502						if (ERROR("SPACING",
4503							  "space prohibited after that '$op' $at\n" . $hereptr)) {
4504							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
4505							if (defined $fix_elements[$n + 2]) {
4506								$fix_elements[$n + 2] =~ s/^\s+//;
4507							}
4508							$line_fixed = 1;
4509						}
4510					}
4511
4512				# unary ++ and unary -- are allowed no space on one side.
4513				} elsif ($op eq '++' or $op eq '--') {
4514					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
4515						if (ERROR("SPACING",
4516							  "space required one side of that '$op' $at\n" . $hereptr)) {
4517							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
4518							$line_fixed = 1;
4519						}
4520					}
4521					if ($ctx =~ /Wx[BE]/ ||
4522					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
4523						if (ERROR("SPACING",
4524							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4525							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4526							$line_fixed = 1;
4527						}
4528					}
4529					if ($ctx =~ /ExW/) {
4530						if (ERROR("SPACING",
4531							  "space prohibited after that '$op' $at\n" . $hereptr)) {
4532							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
4533							if (defined $fix_elements[$n + 2]) {
4534								$fix_elements[$n + 2] =~ s/^\s+//;
4535							}
4536							$line_fixed = 1;
4537						}
4538					}
4539
4540				# << and >> may either have or not have spaces both sides
4541				} elsif ($op eq '<<' or $op eq '>>' or
4542					 $op eq '&' or $op eq '^' or $op eq '|' or
4543					 $op eq '+' or $op eq '-' or
4544					 $op eq '*' or $op eq '/' or
4545					 $op eq '%')
4546				{
4547					if ($check) {
4548						if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
4549							if (CHK("SPACING",
4550								"spaces preferred around that '$op' $at\n" . $hereptr)) {
4551								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4552								$fix_elements[$n + 2] =~ s/^\s+//;
4553								$line_fixed = 1;
4554							}
4555						} elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
4556							if (CHK("SPACING",
4557								"space preferred before that '$op' $at\n" . $hereptr)) {
4558								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
4559								$line_fixed = 1;
4560							}
4561						}
4562					} elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
4563						if (ERROR("SPACING",
4564							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
4565							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4566							if (defined $fix_elements[$n + 2]) {
4567								$fix_elements[$n + 2] =~ s/^\s+//;
4568							}
4569							$line_fixed = 1;
4570						}
4571					}
4572
4573				# A colon needs no spaces before when it is
4574				# terminating a case value or a label.
4575				} elsif ($opv eq ':C' || $opv eq ':L') {
4576					if ($ctx =~ /Wx./) {
4577						if (ERROR("SPACING",
4578							  "space prohibited before that '$op' $at\n" . $hereptr)) {
4579							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
4580							$line_fixed = 1;
4581						}
4582					}
4583
4584				# All the others need spaces both sides.
4585				} elsif ($ctx !~ /[EWC]x[CWE]/) {
4586					my $ok = 0;
4587
4588					# Ignore email addresses <foo@bar>
4589					if (($op eq '<' &&
4590					     $cc =~ /^\S+\@\S+>/) ||
4591					    ($op eq '>' &&
4592					     $ca =~ /<\S+\@\S+$/))
4593					{
4594					    	$ok = 1;
4595					}
4596
4597					# for asm volatile statements
4598					# ignore a colon with another
4599					# colon immediately before or after
4600					if (($op eq ':') &&
4601					    ($ca =~ /:$/ || $cc =~ /^:/)) {
4602						$ok = 1;
4603					}
4604
4605					# messages are ERROR, but ?: are CHK
4606					if ($ok == 0) {
4607						my $msg_level = \&ERROR;
4608						$msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
4609
4610						if (&{$msg_level}("SPACING",
4611								  "spaces required around that '$op' $at\n" . $hereptr)) {
4612							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
4613							if (defined $fix_elements[$n + 2]) {
4614								$fix_elements[$n + 2] =~ s/^\s+//;
4615							}
4616							$line_fixed = 1;
4617						}
4618					}
4619				}
4620				$off += length($elements[$n + 1]);
4621
4622##				print("n: <$n> GOOD: <$good>\n");
4623
4624				$fixed_line = $fixed_line . $good;
4625			}
4626
4627			if (($#elements % 2) == 0) {
4628				$fixed_line = $fixed_line . $fix_elements[$#elements];
4629			}
4630
4631			if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
4632				$fixed[$fixlinenr] = $fixed_line;
4633			}
4634
4635
4636		}
4637
4638# check for whitespace before a non-naked semicolon
4639		if ($line =~ /^\+.*\S\s+;\s*$/) {
4640			if (WARN("SPACING",
4641				 "space prohibited before semicolon\n" . $herecurr) &&
4642			    $fix) {
4643				1 while $fixed[$fixlinenr] =~
4644				    s/^(\+.*\S)\s+;/$1;/;
4645			}
4646		}
4647
4648# check for multiple assignments
4649		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
4650			CHK("MULTIPLE_ASSIGNMENTS",
4651			    "multiple assignments should be avoided\n" . $herecurr);
4652		}
4653
4654## # check for multiple declarations, allowing for a function declaration
4655## # continuation.
4656## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
4657## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
4658##
4659## 			# Remove any bracketed sections to ensure we do not
4660## 			# falsly report the parameters of functions.
4661## 			my $ln = $line;
4662## 			while ($ln =~ s/\([^\(\)]*\)//g) {
4663## 			}
4664## 			if ($ln =~ /,/) {
4665## 				WARN("MULTIPLE_DECLARATION",
4666##				     "declaring multiple variables together should be avoided\n" . $herecurr);
4667## 			}
4668## 		}
4669
4670#need space before brace following if, while, etc
4671		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
4672		    $line =~ /\b(?:else|do)\{/) {
4673			if (ERROR("SPACING",
4674				  "space required before the open brace '{'\n" . $herecurr) &&
4675			    $fix) {
4676				$fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
4677			}
4678		}
4679
4680## # check for blank lines before declarations
4681##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
4682##		    $prevrawline =~ /^.\s*$/) {
4683##			WARN("SPACING",
4684##			     "No blank lines before declarations\n" . $hereprev);
4685##		}
4686##
4687
4688# closing brace should have a space following it when it has anything
4689# on the line
4690		if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
4691			if (ERROR("SPACING",
4692				  "space required after that close brace '}'\n" . $herecurr) &&
4693			    $fix) {
4694				$fixed[$fixlinenr] =~
4695				    s/}((?!(?:,|;|\)))\S)/} $1/;
4696			}
4697		}
4698
4699# check spacing on square brackets
4700		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
4701			if (ERROR("SPACING",
4702				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
4703			    $fix) {
4704				$fixed[$fixlinenr] =~
4705				    s/\[\s+/\[/;
4706			}
4707		}
4708		if ($line =~ /\s\]/) {
4709			if (ERROR("SPACING",
4710				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
4711			    $fix) {
4712				$fixed[$fixlinenr] =~
4713				    s/\s+\]/\]/;
4714			}
4715		}
4716
4717# check spacing on parentheses
4718		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
4719		    $line !~ /for\s*\(\s+;/) {
4720			if (ERROR("SPACING",
4721				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
4722			    $fix) {
4723				$fixed[$fixlinenr] =~
4724				    s/\(\s+/\(/;
4725			}
4726		}
4727		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
4728		    $line !~ /for\s*\(.*;\s+\)/ &&
4729		    $line !~ /:\s+\)/) {
4730			if (ERROR("SPACING",
4731				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
4732			    $fix) {
4733				$fixed[$fixlinenr] =~
4734				    s/\s+\)/\)/;
4735			}
4736		}
4737
4738# check unnecessary parentheses around addressof/dereference single $Lvals
4739# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
4740
4741		while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
4742			my $var = $1;
4743			if (CHK("UNNECESSARY_PARENTHESES",
4744				"Unnecessary parentheses around $var\n" . $herecurr) &&
4745			    $fix) {
4746				$fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
4747			}
4748		}
4749
4750# check for unnecessary parentheses around function pointer uses
4751# ie: (foo->bar)(); should be foo->bar();
4752# but not "if (foo->bar) (" to avoid some false positives
4753		if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
4754			my $var = $2;
4755			if (CHK("UNNECESSARY_PARENTHESES",
4756				"Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
4757			    $fix) {
4758				my $var2 = deparenthesize($var);
4759				$var2 =~ s/\s//g;
4760				$fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
4761			}
4762		}
4763
4764# check for unnecessary parentheses around comparisons in if uses
4765# when !drivers/staging or command-line uses --strict
4766		if (($realfile !~ m@^(?:drivers/staging/)@ || $check_orig) &&
4767		    $perl_version_ok && defined($stat) &&
4768		    $stat =~ /(^.\s*if\s*($balanced_parens))/) {
4769			my $if_stat = $1;
4770			my $test = substr($2, 1, -1);
4771			my $herectx;
4772			while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
4773				my $match = $1;
4774				# avoid parentheses around potential macro args
4775				next if ($match =~ /^\s*\w+\s*$/);
4776				if (!defined($herectx)) {
4777					$herectx = $here . "\n";
4778					my $cnt = statement_rawlines($if_stat);
4779					for (my $n = 0; $n < $cnt; $n++) {
4780						my $rl = raw_line($linenr, $n);
4781						$herectx .=  $rl . "\n";
4782						last if $rl =~ /^[ \+].*\{/;
4783					}
4784				}
4785				CHK("UNNECESSARY_PARENTHESES",
4786				    "Unnecessary parentheses around '$match'\n" . $herectx);
4787			}
4788		}
4789
4790#goto labels aren't indented, allow a single space however
4791		if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
4792		   !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
4793			if (WARN("INDENTED_LABEL",
4794				 "labels should not be indented\n" . $herecurr) &&
4795			    $fix) {
4796				$fixed[$fixlinenr] =~
4797				    s/^(.)\s+/$1/;
4798			}
4799		}
4800
4801# return is not a function
4802		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
4803			my $spacing = $1;
4804			if ($perl_version_ok &&
4805			    $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
4806				my $value = $1;
4807				$value = deparenthesize($value);
4808				if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
4809					ERROR("RETURN_PARENTHESES",
4810					      "return is not a function, parentheses are not required\n" . $herecurr);
4811				}
4812			} elsif ($spacing !~ /\s+/) {
4813				ERROR("SPACING",
4814				      "space required before the open parenthesis '('\n" . $herecurr);
4815			}
4816		}
4817
4818# unnecessary return in a void function
4819# at end-of-function, with the previous line a single leading tab, then return;
4820# and the line before that not a goto label target like "out:"
4821		if ($sline =~ /^[ \+]}\s*$/ &&
4822		    $prevline =~ /^\+\treturn\s*;\s*$/ &&
4823		    $linenr >= 3 &&
4824		    $lines[$linenr - 3] =~ /^[ +]/ &&
4825		    $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
4826			WARN("RETURN_VOID",
4827			     "void function return statements are not generally useful\n" . $hereprev);
4828               }
4829
4830# if statements using unnecessary parentheses - ie: if ((foo == bar))
4831		if ($perl_version_ok &&
4832		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
4833			my $openparens = $1;
4834			my $count = $openparens =~ tr@\(@\(@;
4835			my $msg = "";
4836			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
4837				my $comp = $4;	#Not $1 because of $LvalOrFunc
4838				$msg = " - maybe == should be = ?" if ($comp eq "==");
4839				WARN("UNNECESSARY_PARENTHESES",
4840				     "Unnecessary parentheses$msg\n" . $herecurr);
4841			}
4842		}
4843
4844# comparisons with a constant or upper case identifier on the left
4845#	avoid cases like "foo + BAR < baz"
4846#	only fix matches surrounded by parentheses to avoid incorrect
4847#	conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
4848		if ($perl_version_ok &&
4849		    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
4850			my $lead = $1;
4851			my $const = $2;
4852			my $comp = $3;
4853			my $to = $4;
4854			my $newcomp = $comp;
4855			if ($lead !~ /(?:$Operators|\.)\s*$/ &&
4856			    $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
4857			    WARN("CONSTANT_COMPARISON",
4858				 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
4859			    $fix) {
4860				if ($comp eq "<") {
4861					$newcomp = ">";
4862				} elsif ($comp eq "<=") {
4863					$newcomp = ">=";
4864				} elsif ($comp eq ">") {
4865					$newcomp = "<";
4866				} elsif ($comp eq ">=") {
4867					$newcomp = "<=";
4868				}
4869				$fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
4870			}
4871		}
4872
4873# Return of what appears to be an errno should normally be negative
4874		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
4875			my $name = $1;
4876			if ($name ne 'EOF' && $name ne 'ERROR') {
4877				WARN("USE_NEGATIVE_ERRNO",
4878				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
4879			}
4880		}
4881
4882# Need a space before open parenthesis after if, while etc
4883		if ($line =~ /\b(if|while|for|switch)\(/) {
4884			if (ERROR("SPACING",
4885				  "space required before the open parenthesis '('\n" . $herecurr) &&
4886			    $fix) {
4887				$fixed[$fixlinenr] =~
4888				    s/\b(if|while|for|switch)\(/$1 \(/;
4889			}
4890		}
4891
4892# Check for illegal assignment in if conditional -- and check for trailing
4893# statements after the conditional.
4894		if ($line =~ /do\s*(?!{)/) {
4895			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4896				ctx_statement_block($linenr, $realcnt, 0)
4897					if (!defined $stat);
4898			my ($stat_next) = ctx_statement_block($line_nr_next,
4899						$remain_next, $off_next);
4900			$stat_next =~ s/\n./\n /g;
4901			##print "stat<$stat> stat_next<$stat_next>\n";
4902
4903			if ($stat_next =~ /^\s*while\b/) {
4904				# If the statement carries leading newlines,
4905				# then count those as offsets.
4906				my ($whitespace) =
4907					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
4908				my $offset =
4909					statement_rawlines($whitespace) - 1;
4910
4911				$suppress_whiletrailers{$line_nr_next +
4912								$offset} = 1;
4913			}
4914		}
4915		if (!defined $suppress_whiletrailers{$linenr} &&
4916		    defined($stat) && defined($cond) &&
4917		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
4918			my ($s, $c) = ($stat, $cond);
4919
4920			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
4921				ERROR("ASSIGN_IN_IF",
4922				      "do not use assignment in if condition\n" . $herecurr);
4923			}
4924
4925			# Find out what is on the end of the line after the
4926			# conditional.
4927			substr($s, 0, length($c), '');
4928			$s =~ s/\n.*//g;
4929			$s =~ s/$;//g; 	# Remove any comments
4930			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
4931			    $c !~ /}\s*while\s*/)
4932			{
4933				# Find out how long the conditional actually is.
4934				my @newlines = ($c =~ /\n/gs);
4935				my $cond_lines = 1 + $#newlines;
4936				my $stat_real = '';
4937
4938				$stat_real = raw_line($linenr, $cond_lines)
4939							. "\n" if ($cond_lines);
4940				if (defined($stat_real) && $cond_lines > 1) {
4941					$stat_real = "[...]\n$stat_real";
4942				}
4943
4944				ERROR("TRAILING_STATEMENTS",
4945				      "trailing statements should be on next line\n" . $herecurr . $stat_real);
4946			}
4947		}
4948
4949# Check for bitwise tests written as boolean
4950		if ($line =~ /
4951			(?:
4952				(?:\[|\(|\&\&|\|\|)
4953				\s*0[xX][0-9]+\s*
4954				(?:\&\&|\|\|)
4955			|
4956				(?:\&\&|\|\|)
4957				\s*0[xX][0-9]+\s*
4958				(?:\&\&|\|\||\)|\])
4959			)/x)
4960		{
4961			WARN("HEXADECIMAL_BOOLEAN_TEST",
4962			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
4963		}
4964
4965# if and else should not have general statements after it
4966		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
4967			my $s = $1;
4968			$s =~ s/$;//g; 	# Remove any comments
4969			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
4970				ERROR("TRAILING_STATEMENTS",
4971				      "trailing statements should be on next line\n" . $herecurr);
4972			}
4973		}
4974# if should not continue a brace
4975		if ($line =~ /}\s*if\b/) {
4976			ERROR("TRAILING_STATEMENTS",
4977			      "trailing statements should be on next line (or did you mean 'else if'?)\n" .
4978				$herecurr);
4979		}
4980# case and default should not have general statements after them
4981		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
4982		    $line !~ /\G(?:
4983			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
4984			\s*return\s+
4985		    )/xg)
4986		{
4987			ERROR("TRAILING_STATEMENTS",
4988			      "trailing statements should be on next line\n" . $herecurr);
4989		}
4990
4991		# Check for }<nl>else {, these must be at the same
4992		# indent level to be relevant to each other.
4993		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
4994		    $previndent == $indent) {
4995			if (ERROR("ELSE_AFTER_BRACE",
4996				  "else should follow close brace '}'\n" . $hereprev) &&
4997			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4998				fix_delete_line($fixlinenr - 1, $prevrawline);
4999				fix_delete_line($fixlinenr, $rawline);
5000				my $fixedline = $prevrawline;
5001				$fixedline =~ s/}\s*$//;
5002				if ($fixedline !~ /^\+\s*$/) {
5003					fix_insert_line($fixlinenr, $fixedline);
5004				}
5005				$fixedline = $rawline;
5006				$fixedline =~ s/^(.\s*)else/$1} else/;
5007				fix_insert_line($fixlinenr, $fixedline);
5008			}
5009		}
5010
5011		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5012		    $previndent == $indent) {
5013			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5014
5015			# Find out what is on the end of the line after the
5016			# conditional.
5017			substr($s, 0, length($c), '');
5018			$s =~ s/\n.*//g;
5019
5020			if ($s =~ /^\s*;/) {
5021				if (ERROR("WHILE_AFTER_BRACE",
5022					  "while should follow close brace '}'\n" . $hereprev) &&
5023				    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5024					fix_delete_line($fixlinenr - 1, $prevrawline);
5025					fix_delete_line($fixlinenr, $rawline);
5026					my $fixedline = $prevrawline;
5027					my $trailing = $rawline;
5028					$trailing =~ s/^\+//;
5029					$trailing = trim($trailing);
5030					$fixedline =~ s/}\s*$/} $trailing/;
5031					fix_insert_line($fixlinenr, $fixedline);
5032				}
5033			}
5034		}
5035
5036#Specific variable tests
5037		while ($line =~ m{($Constant|$Lval)}g) {
5038			my $var = $1;
5039
5040#CamelCase
5041			if ($var !~ /^$Constant$/ &&
5042			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5043#Ignore Page<foo> variants
5044			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5045#Ignore SI style variants like nS, mV and dB
5046#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5047			    $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5048#Ignore some three character SI units explicitly, like MiB and KHz
5049			    $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5050				while ($var =~ m{($Ident)}g) {
5051					my $word = $1;
5052					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5053					if ($check) {
5054						seed_camelcase_includes();
5055						if (!$file && !$camelcase_file_seeded) {
5056							seed_camelcase_file($realfile);
5057							$camelcase_file_seeded = 1;
5058						}
5059					}
5060					if (!defined $camelcase{$word}) {
5061						$camelcase{$word} = 1;
5062						CHK("CAMELCASE",
5063						    "Avoid CamelCase: <$word>\n" . $herecurr);
5064					}
5065				}
5066			}
5067		}
5068
5069#no spaces allowed after \ in define
5070		if ($line =~ /\#\s*define.*\\\s+$/) {
5071			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5072				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5073			    $fix) {
5074				$fixed[$fixlinenr] =~ s/\s+$//;
5075			}
5076		}
5077
5078# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5079# itself <asm/foo.h> (uses RAW line)
5080		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5081			my $file = "$1.h";
5082			my $checkfile = "include/linux/$file";
5083			if (-f "$root/$checkfile" &&
5084			    $realfile ne $checkfile &&
5085			    $1 !~ /$allowed_asm_includes/)
5086			{
5087				my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5088				if ($asminclude > 0) {
5089					if ($realfile =~ m{^arch/}) {
5090						CHK("ARCH_INCLUDE_LINUX",
5091						    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5092					} else {
5093						WARN("INCLUDE_LINUX",
5094						     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5095					}
5096				}
5097			}
5098		}
5099
5100# multi-statement macros should be enclosed in a do while loop, grab the
5101# first statement and ensure its the whole macro if its not enclosed
5102# in a known good container
5103		if ($realfile !~ m@/vmlinux.lds.h$@ &&
5104		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5105			my $ln = $linenr;
5106			my $cnt = $realcnt;
5107			my ($off, $dstat, $dcond, $rest);
5108			my $ctx = '';
5109			my $has_flow_statement = 0;
5110			my $has_arg_concat = 0;
5111			($dstat, $dcond, $ln, $cnt, $off) =
5112				ctx_statement_block($linenr, $realcnt, 0);
5113			$ctx = $dstat;
5114			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5115			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5116
5117			$has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5118			$has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5119
5120			$dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5121			my $define_args = $1;
5122			my $define_stmt = $dstat;
5123			my @def_args = ();
5124
5125			if (defined $define_args && $define_args ne "") {
5126				$define_args = substr($define_args, 1, length($define_args) - 2);
5127				$define_args =~ s/\s*//g;
5128				$define_args =~ s/\\\+?//g;
5129				@def_args = split(",", $define_args);
5130			}
5131
5132			$dstat =~ s/$;//g;
5133			$dstat =~ s/\\\n.//g;
5134			$dstat =~ s/^\s*//s;
5135			$dstat =~ s/\s*$//s;
5136
5137			# Flatten any parentheses and braces
5138			while ($dstat =~ s/\([^\(\)]*\)/1/ ||
5139			       $dstat =~ s/\{[^\{\}]*\}/1/ ||
5140			       $dstat =~ s/.\[[^\[\]]*\]/1/)
5141			{
5142			}
5143
5144			# Flatten any obvious string concatentation.
5145			while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5146			       $dstat =~ s/$Ident\s*($String)/$1/)
5147			{
5148			}
5149
5150			# Make asm volatile uses seem like a generic function
5151			$dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5152
5153			my $exceptions = qr{
5154				$Declare|
5155				module_param_named|
5156				MODULE_PARM_DESC|
5157				DECLARE_PER_CPU|
5158				DEFINE_PER_CPU|
5159				__typeof__\(|
5160				union|
5161				struct|
5162				\.$Ident\s*=\s*|
5163				^\"|\"$|
5164				^\[
5165			}x;
5166			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
5167
5168			$ctx =~ s/\n*$//;
5169			my $stmt_cnt = statement_rawlines($ctx);
5170			my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
5171
5172			if ($dstat ne '' &&
5173			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
5174			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
5175			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
5176			    $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&			# character constants
5177			    $dstat !~ /$exceptions/ &&
5178			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
5179			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
5180			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
5181			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
5182			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
5183			    $dstat !~ /^do\s*{/ &&					# do {...
5184			    $dstat !~ /^\(\{/ &&						# ({...
5185			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
5186			{
5187				if ($dstat =~ /^\s*if\b/) {
5188					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5189					      "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
5190				} elsif ($dstat =~ /;/) {
5191					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
5192					      "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx");
5193				} else {
5194					ERROR("COMPLEX_MACRO",
5195					      "Macros with complex values should be enclosed in parentheses\n" . "$herectx");
5196				}
5197
5198			}
5199
5200			# Make $define_stmt single line, comment-free, etc
5201			my @stmt_array = split('\n', $define_stmt);
5202			my $first = 1;
5203			$define_stmt = "";
5204			foreach my $l (@stmt_array) {
5205				$l =~ s/\\$//;
5206				if ($first) {
5207					$define_stmt = $l;
5208					$first = 0;
5209				} elsif ($l =~ /^[\+ ]/) {
5210					$define_stmt .= substr($l, 1);
5211				}
5212			}
5213			$define_stmt =~ s/$;//g;
5214			$define_stmt =~ s/\s+/ /g;
5215			$define_stmt = trim($define_stmt);
5216
5217# check if any macro arguments are reused (ignore '...' and 'type')
5218			foreach my $arg (@def_args) {
5219			        next if ($arg =~ /\.\.\./);
5220			        next if ($arg =~ /^type$/i);
5221				my $tmp_stmt = $define_stmt;
5222				$tmp_stmt =~ s/\b(sizeof|typeof|__typeof__|__builtin\w+|typecheck\s*\(\s*$Type\s*,|\#+)\s*\(*\s*$arg\s*\)*\b//g;
5223				$tmp_stmt =~ s/\#+\s*$arg\b//g;
5224				$tmp_stmt =~ s/\b$arg\s*\#\#//g;
5225				my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
5226				if ($use_cnt > 1) {
5227					CHK("MACRO_ARG_REUSE",
5228					    "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
5229				    }
5230# check if any macro arguments may have other precedence issues
5231				if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
5232				    ((defined($1) && $1 ne ',') ||
5233				     (defined($2) && $2 ne ','))) {
5234					CHK("MACRO_ARG_PRECEDENCE",
5235					    "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
5236				}
5237			}
5238
5239# check for macros with flow control, but without ## concatenation
5240# ## concatenation is commonly a macro that defines a function so ignore those
5241			if ($has_flow_statement && !$has_arg_concat) {
5242				my $cnt = statement_rawlines($ctx);
5243				my $herectx = get_stat_here($linenr, $cnt, $here);
5244
5245				WARN("MACRO_WITH_FLOW_CONTROL",
5246				     "Macros with flow control statements should be avoided\n" . "$herectx");
5247			}
5248
5249# check for line continuations outside of #defines, preprocessor #, and asm
5250
5251		} else {
5252			if ($prevline !~ /^..*\\$/ &&
5253			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
5254			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
5255			    $line =~ /^\+.*\\$/) {
5256				WARN("LINE_CONTINUATIONS",
5257				     "Avoid unnecessary line continuations\n" . $herecurr);
5258			}
5259		}
5260
5261# do {} while (0) macro tests:
5262# single-statement macros do not need to be enclosed in do while (0) loop,
5263# macro should not end with a semicolon
5264		if ($perl_version_ok &&
5265		    $realfile !~ m@/vmlinux.lds.h$@ &&
5266		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
5267			my $ln = $linenr;
5268			my $cnt = $realcnt;
5269			my ($off, $dstat, $dcond, $rest);
5270			my $ctx = '';
5271			($dstat, $dcond, $ln, $cnt, $off) =
5272				ctx_statement_block($linenr, $realcnt, 0);
5273			$ctx = $dstat;
5274
5275			$dstat =~ s/\\\n.//g;
5276			$dstat =~ s/$;/ /g;
5277
5278			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
5279				my $stmts = $2;
5280				my $semis = $3;
5281
5282				$ctx =~ s/\n*$//;
5283				my $cnt = statement_rawlines($ctx);
5284				my $herectx = get_stat_here($linenr, $cnt, $here);
5285
5286				if (($stmts =~ tr/;/;/) == 1 &&
5287				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
5288					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
5289					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
5290				}
5291				if (defined $semis && $semis ne "") {
5292					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
5293					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
5294				}
5295			} elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
5296				$ctx =~ s/\n*$//;
5297				my $cnt = statement_rawlines($ctx);
5298				my $herectx = get_stat_here($linenr, $cnt, $here);
5299
5300				WARN("TRAILING_SEMICOLON",
5301				     "macros should not use a trailing semicolon\n" . "$herectx");
5302			}
5303		}
5304
5305# check for redundant bracing round if etc
5306		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
5307			my ($level, $endln, @chunks) =
5308				ctx_statement_full($linenr, $realcnt, 1);
5309			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
5310			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
5311			if ($#chunks > 0 && $level == 0) {
5312				my @allowed = ();
5313				my $allow = 0;
5314				my $seen = 0;
5315				my $herectx = $here . "\n";
5316				my $ln = $linenr - 1;
5317				for my $chunk (@chunks) {
5318					my ($cond, $block) = @{$chunk};
5319
5320					# If the condition carries leading newlines, then count those as offsets.
5321					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
5322					my $offset = statement_rawlines($whitespace) - 1;
5323
5324					$allowed[$allow] = 0;
5325					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
5326
5327					# We have looked at and allowed this specific line.
5328					$suppress_ifbraces{$ln + $offset} = 1;
5329
5330					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
5331					$ln += statement_rawlines($block) - 1;
5332
5333					substr($block, 0, length($cond), '');
5334
5335					$seen++ if ($block =~ /^\s*{/);
5336
5337					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
5338					if (statement_lines($cond) > 1) {
5339						#print "APW: ALLOWED: cond<$cond>\n";
5340						$allowed[$allow] = 1;
5341					}
5342					if ($block =~/\b(?:if|for|while)\b/) {
5343						#print "APW: ALLOWED: block<$block>\n";
5344						$allowed[$allow] = 1;
5345					}
5346					if (statement_block_size($block) > 1) {
5347						#print "APW: ALLOWED: lines block<$block>\n";
5348						$allowed[$allow] = 1;
5349					}
5350					$allow++;
5351				}
5352				if ($seen) {
5353					my $sum_allowed = 0;
5354					foreach (@allowed) {
5355						$sum_allowed += $_;
5356					}
5357					if ($sum_allowed == 0) {
5358						WARN("BRACES",
5359						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
5360					} elsif ($sum_allowed != $allow &&
5361						 $seen != $allow) {
5362						CHK("BRACES",
5363						    "braces {} should be used on all arms of this statement\n" . $herectx);
5364					}
5365				}
5366			}
5367		}
5368		if (!defined $suppress_ifbraces{$linenr - 1} &&
5369					$line =~ /\b(if|while|for|else)\b/) {
5370			my $allowed = 0;
5371
5372			# Check the pre-context.
5373			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
5374				#print "APW: ALLOWED: pre<$1>\n";
5375				$allowed = 1;
5376			}
5377
5378			my ($level, $endln, @chunks) =
5379				ctx_statement_full($linenr, $realcnt, $-[0]);
5380
5381			# Check the condition.
5382			my ($cond, $block) = @{$chunks[0]};
5383			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
5384			if (defined $cond) {
5385				substr($block, 0, length($cond), '');
5386			}
5387			if (statement_lines($cond) > 1) {
5388				#print "APW: ALLOWED: cond<$cond>\n";
5389				$allowed = 1;
5390			}
5391			if ($block =~/\b(?:if|for|while)\b/) {
5392				#print "APW: ALLOWED: block<$block>\n";
5393				$allowed = 1;
5394			}
5395			if (statement_block_size($block) > 1) {
5396				#print "APW: ALLOWED: lines block<$block>\n";
5397				$allowed = 1;
5398			}
5399			# Check the post-context.
5400			if (defined $chunks[1]) {
5401				my ($cond, $block) = @{$chunks[1]};
5402				if (defined $cond) {
5403					substr($block, 0, length($cond), '');
5404				}
5405				if ($block =~ /^\s*\{/) {
5406					#print "APW: ALLOWED: chunk-1 block<$block>\n";
5407					$allowed = 1;
5408				}
5409			}
5410			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
5411				my $cnt = statement_rawlines($block);
5412				my $herectx = get_stat_here($linenr, $cnt, $here);
5413
5414				WARN("BRACES",
5415				     "braces {} are not necessary for single statement blocks\n" . $herectx);
5416			}
5417		}
5418
5419# check for single line unbalanced braces
5420		if ($sline =~ /^.\s*\}\s*else\s*$/ ||
5421		    $sline =~ /^.\s*else\s*\{\s*$/) {
5422			CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
5423		}
5424
5425# check for unnecessary blank lines around braces
5426		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
5427			if (CHK("BRACES",
5428				"Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
5429			    $fix && $prevrawline =~ /^\+/) {
5430				fix_delete_line($fixlinenr - 1, $prevrawline);
5431			}
5432		}
5433		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
5434			if (CHK("BRACES",
5435				"Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
5436			    $fix) {
5437				fix_delete_line($fixlinenr, $rawline);
5438			}
5439		}
5440
5441# no volatiles please
5442		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
5443		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
5444			WARN("VOLATILE",
5445			     "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
5446		}
5447
5448# Check for user-visible strings broken across lines, which breaks the ability
5449# to grep for the string.  Make exceptions when the previous string ends in a
5450# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
5451# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
5452		if ($line =~ /^\+\s*$String/ &&
5453		    $prevline =~ /"\s*$/ &&
5454		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
5455			if (WARN("SPLIT_STRING",
5456				 "quoted string split across lines\n" . $hereprev) &&
5457				     $fix &&
5458				     $prevrawline =~ /^\+.*"\s*$/ &&
5459				     $last_coalesced_string_linenr != $linenr - 1) {
5460				my $extracted_string = get_quoted_string($line, $rawline);
5461				my $comma_close = "";
5462				if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
5463					$comma_close = $1;
5464				}
5465
5466				fix_delete_line($fixlinenr - 1, $prevrawline);
5467				fix_delete_line($fixlinenr, $rawline);
5468				my $fixedline = $prevrawline;
5469				$fixedline =~ s/"\s*$//;
5470				$fixedline .= substr($extracted_string, 1) . trim($comma_close);
5471				fix_insert_line($fixlinenr - 1, $fixedline);
5472				$fixedline = $rawline;
5473				$fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
5474				if ($fixedline !~ /\+\s*$/) {
5475					fix_insert_line($fixlinenr, $fixedline);
5476				}
5477				$last_coalesced_string_linenr = $linenr;
5478			}
5479		}
5480
5481# check for missing a space in a string concatenation
5482		if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
5483			WARN('MISSING_SPACE',
5484			     "break quoted strings at a space character\n" . $hereprev);
5485		}
5486
5487# check for an embedded function name in a string when the function is known
5488# This does not work very well for -f --file checking as it depends on patch
5489# context providing the function name or a single line form for in-file
5490# function declarations
5491		if ($line =~ /^\+.*$String/ &&
5492		    defined($context_function) &&
5493		    get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
5494		    length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
5495			WARN("EMBEDDED_FUNCTION_NAME",
5496			     "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
5497		}
5498
5499# check for spaces before a quoted newline
5500		if ($rawline =~ /^.*\".*\s\\n/) {
5501			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
5502				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
5503			    $fix) {
5504				$fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
5505			}
5506
5507		}
5508
5509# concatenated string without spaces between elements
5510		if ($line =~ /$String[A-Za-z0-9_]/ || $line =~ /[A-Za-z0-9_]$String/) {
5511			if (CHK("CONCATENATED_STRING",
5512				"Concatenated strings should use spaces between elements\n" . $herecurr) &&
5513			    $fix) {
5514				while ($line =~ /($String)/g) {
5515					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5516					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
5517					$fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
5518				}
5519			}
5520		}
5521
5522# uncoalesced string fragments
5523		if ($line =~ /$String\s*"/) {
5524			if (WARN("STRING_FRAGMENTS",
5525				 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
5526			    $fix) {
5527				while ($line =~ /($String)(?=\s*")/g) {
5528					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
5529					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
5530				}
5531			}
5532		}
5533
5534# check for non-standard and hex prefixed decimal printf formats
5535		my $show_L = 1;	#don't show the same defect twice
5536		my $show_Z = 1;
5537		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
5538			my $string = substr($rawline, $-[1], $+[1] - $-[1]);
5539			$string =~ s/%%/__/g;
5540			# check for %L
5541			if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
5542				WARN("PRINTF_L",
5543				     "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
5544				$show_L = 0;
5545			}
5546			# check for %Z
5547			if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
5548				WARN("PRINTF_Z",
5549				     "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
5550				$show_Z = 0;
5551			}
5552			# check for 0x<decimal>
5553			if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
5554				ERROR("PRINTF_0XDECIMAL",
5555				      "Prefixing 0x with decimal output is defective\n" . $herecurr);
5556			}
5557		}
5558
5559# check for line continuations in quoted strings with odd counts of "
5560		if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
5561			WARN("LINE_CONTINUATIONS",
5562			     "Avoid line continuations in quoted strings\n" . $herecurr);
5563		}
5564
5565# warn about #if 0
5566		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
5567			WARN("IF_0",
5568			     "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
5569		}
5570
5571# warn about #if 1
5572		if ($line =~ /^.\s*\#\s*if\s+1\b/) {
5573			WARN("IF_1",
5574			     "Consider removing the #if 1 and its #endif\n" . $herecurr);
5575		}
5576
5577# check for needless "if (<foo>) fn(<foo>)" uses
5578		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
5579			my $tested = quotemeta($1);
5580			my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
5581			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
5582				my $func = $1;
5583				if (WARN('NEEDLESS_IF',
5584					 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
5585				    $fix) {
5586					my $do_fix = 1;
5587					my $leading_tabs = "";
5588					my $new_leading_tabs = "";
5589					if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
5590						$leading_tabs = $1;
5591					} else {
5592						$do_fix = 0;
5593					}
5594					if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
5595						$new_leading_tabs = $1;
5596						if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
5597							$do_fix = 0;
5598						}
5599					} else {
5600						$do_fix = 0;
5601					}
5602					if ($do_fix) {
5603						fix_delete_line($fixlinenr - 1, $prevrawline);
5604						$fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
5605					}
5606				}
5607			}
5608		}
5609
5610# check for unnecessary "Out of Memory" messages
5611		if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
5612		    $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
5613		    (defined $1 || defined $3) &&
5614		    $linenr > 3) {
5615			my $testval = $2;
5616			my $testline = $lines[$linenr - 3];
5617
5618			my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
5619#			print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
5620
5621			if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
5622			    $s !~ /\b__GFP_NOWARN\b/ ) {
5623				WARN("OOM_MESSAGE",
5624				     "Possible unnecessary 'out of memory' message\n" . $hereprev);
5625			}
5626		}
5627
5628# check for logging functions with KERN_<LEVEL>
5629		if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
5630		    $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
5631			my $level = $1;
5632			if (WARN("UNNECESSARY_KERN_LEVEL",
5633				 "Possible unnecessary $level\n" . $herecurr) &&
5634			    $fix) {
5635				$fixed[$fixlinenr] =~ s/\s*$level\s*//;
5636			}
5637		}
5638
5639# check for logging continuations
5640		if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
5641			WARN("LOGGING_CONTINUATION",
5642			     "Avoid logging continuation uses where feasible\n" . $herecurr);
5643		}
5644
5645# check for mask then right shift without a parentheses
5646		if ($perl_version_ok &&
5647		    $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
5648		    $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
5649			WARN("MASK_THEN_SHIFT",
5650			     "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
5651		}
5652
5653# check for pointer comparisons to NULL
5654		if ($perl_version_ok) {
5655			while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
5656				my $val = $1;
5657				my $equal = "!";
5658				$equal = "" if ($4 eq "!=");
5659				if (CHK("COMPARISON_TO_NULL",
5660					"Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
5661					    $fix) {
5662					$fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
5663				}
5664			}
5665		}
5666
5667# check for bad placement of section $InitAttribute (e.g.: __initdata)
5668		if ($line =~ /(\b$InitAttribute\b)/) {
5669			my $attr = $1;
5670			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
5671				my $ptr = $1;
5672				my $var = $2;
5673				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
5674				      ERROR("MISPLACED_INIT",
5675					    "$attr should be placed after $var\n" . $herecurr)) ||
5676				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
5677				      WARN("MISPLACED_INIT",
5678					   "$attr should be placed after $var\n" . $herecurr))) &&
5679				    $fix) {
5680					$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;
5681				}
5682			}
5683		}
5684
5685# check for $InitAttributeData (ie: __initdata) with const
5686		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
5687			my $attr = $1;
5688			$attr =~ /($InitAttributePrefix)(.*)/;
5689			my $attr_prefix = $1;
5690			my $attr_type = $2;
5691			if (ERROR("INIT_ATTRIBUTE",
5692				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
5693			    $fix) {
5694				$fixed[$fixlinenr] =~
5695				    s/$InitAttributeData/${attr_prefix}initconst/;
5696			}
5697		}
5698
5699# check for $InitAttributeConst (ie: __initconst) without const
5700		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
5701			my $attr = $1;
5702			if (ERROR("INIT_ATTRIBUTE",
5703				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
5704			    $fix) {
5705				my $lead = $fixed[$fixlinenr] =~
5706				    /(^\+\s*(?:static\s+))/;
5707				$lead = rtrim($1);
5708				$lead = "$lead " if ($lead !~ /^\+$/);
5709				$lead = "${lead}const ";
5710				$fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
5711			}
5712		}
5713
5714# check for __read_mostly with const non-pointer (should just be const)
5715		if ($line =~ /\b__read_mostly\b/ &&
5716		    $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
5717			if (ERROR("CONST_READ_MOSTLY",
5718				  "Invalid use of __read_mostly with const type\n" . $herecurr) &&
5719			    $fix) {
5720				$fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
5721			}
5722		}
5723
5724# don't use __constant_<foo> functions outside of include/uapi/
5725		if ($realfile !~ m@^include/uapi/@ &&
5726		    $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
5727			my $constant_func = $1;
5728			my $func = $constant_func;
5729			$func =~ s/^__constant_//;
5730			if (WARN("CONSTANT_CONVERSION",
5731				 "$constant_func should be $func\n" . $herecurr) &&
5732			    $fix) {
5733				$fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
5734			}
5735		}
5736
5737# prefer usleep_range over udelay
5738		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
5739			my $delay = $1;
5740			# ignore udelay's < 10, however
5741			if (! ($delay < 10) ) {
5742				CHK("USLEEP_RANGE",
5743				    "usleep_range is preferred over udelay; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5744			}
5745			if ($delay > 2000) {
5746				WARN("LONG_UDELAY",
5747				     "long udelay - prefer mdelay; see arch/arm/include/asm/delay.h\n" . $herecurr);
5748			}
5749		}
5750
5751# warn about unexpectedly long msleep's
5752		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
5753			if ($1 < 20) {
5754				WARN("MSLEEP",
5755				     "msleep < 20ms can sleep for up to 20ms; see Documentation/timers/timers-howto.rst\n" . $herecurr);
5756			}
5757		}
5758
5759# check for comparisons of jiffies
5760		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
5761			WARN("JIFFIES_COMPARISON",
5762			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
5763		}
5764
5765# check for comparisons of get_jiffies_64()
5766		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
5767			WARN("JIFFIES_COMPARISON",
5768			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
5769		}
5770
5771# warn about #ifdefs in C files
5772#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
5773#			print "#ifdef in C files should be avoided\n";
5774#			print "$herecurr";
5775#			$clean = 0;
5776#		}
5777
5778# warn about spacing in #ifdefs
5779		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
5780			if (ERROR("SPACING",
5781				  "exactly one space required after that #$1\n" . $herecurr) &&
5782			    $fix) {
5783				$fixed[$fixlinenr] =~
5784				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
5785			}
5786
5787		}
5788
5789# check for spinlock_t definitions without a comment.
5790		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
5791		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
5792			my $which = $1;
5793			if (!ctx_has_comment($first_line, $linenr)) {
5794				CHK("UNCOMMENTED_DEFINITION",
5795				    "$1 definition without comment\n" . $herecurr);
5796			}
5797		}
5798# check for memory barriers without a comment.
5799
5800		my $barriers = qr{
5801			mb|
5802			rmb|
5803			wmb|
5804			read_barrier_depends
5805		}x;
5806		my $barrier_stems = qr{
5807			mb__before_atomic|
5808			mb__after_atomic|
5809			store_release|
5810			load_acquire|
5811			store_mb|
5812			(?:$barriers)
5813		}x;
5814		my $all_barriers = qr{
5815			(?:$barriers)|
5816			smp_(?:$barrier_stems)|
5817			virt_(?:$barrier_stems)
5818		}x;
5819
5820		if ($line =~ /\b(?:$all_barriers)\s*\(/) {
5821			if (!ctx_has_comment($first_line, $linenr)) {
5822				WARN("MEMORY_BARRIER",
5823				     "memory barrier without comment\n" . $herecurr);
5824			}
5825		}
5826
5827		my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
5828
5829		if ($realfile !~ m@^include/asm-generic/@ &&
5830		    $realfile !~ m@/barrier\.h$@ &&
5831		    $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
5832		    $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
5833			WARN("MEMORY_BARRIER",
5834			     "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
5835		}
5836
5837# check for waitqueue_active without a comment.
5838		if ($line =~ /\bwaitqueue_active\s*\(/) {
5839			if (!ctx_has_comment($first_line, $linenr)) {
5840				WARN("WAITQUEUE_ACTIVE",
5841				     "waitqueue_active without comment\n" . $herecurr);
5842			}
5843		}
5844
5845# check for smp_read_barrier_depends and read_barrier_depends
5846		if (!$file && $line =~ /\b(smp_|)read_barrier_depends\s*\(/) {
5847			WARN("READ_BARRIER_DEPENDS",
5848			     "$1read_barrier_depends should only be used in READ_ONCE or DEC Alpha code\n" . $herecurr);
5849		}
5850
5851# check of hardware specific defines
5852		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
5853			CHK("ARCH_DEFINES",
5854			    "architecture specific defines should be avoided\n" .  $herecurr);
5855		}
5856
5857# check that the storage class is not after a type
5858		if ($line =~ /\b($Type)\s+($Storage)\b/) {
5859			WARN("STORAGE_CLASS",
5860			     "storage class '$2' should be located before type '$1'\n" . $herecurr);
5861		}
5862# Check that the storage class is at the beginning of a declaration
5863		if ($line =~ /\b$Storage\b/ &&
5864		    $line !~ /^.\s*$Storage/ &&
5865		    $line =~ /^.\s*(.+?)\$Storage\s/ &&
5866		    $1 !~ /[\,\)]\s*$/) {
5867			WARN("STORAGE_CLASS",
5868			     "storage class should be at the beginning of the declaration\n" . $herecurr);
5869		}
5870
5871# check the location of the inline attribute, that it is between
5872# storage class and type.
5873		if ($line =~ /\b$Type\s+$Inline\b/ ||
5874		    $line =~ /\b$Inline\s+$Storage\b/) {
5875			ERROR("INLINE_LOCATION",
5876			      "inline keyword should sit between storage class and type\n" . $herecurr);
5877		}
5878
5879# Check for __inline__ and __inline, prefer inline
5880		if ($realfile !~ m@\binclude/uapi/@ &&
5881		    $line =~ /\b(__inline__|__inline)\b/) {
5882			if (WARN("INLINE",
5883				 "plain inline is preferred over $1\n" . $herecurr) &&
5884			    $fix) {
5885				$fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
5886
5887			}
5888		}
5889
5890# Check for __attribute__ packed, prefer __packed
5891		if ($realfile !~ m@\binclude/uapi/@ &&
5892		    $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) {
5893			WARN("PREFER_PACKED",
5894			     "__packed is preferred over __attribute__((packed))\n" . $herecurr);
5895		}
5896
5897# Check for __attribute__ aligned, prefer __aligned
5898		if ($realfile !~ m@\binclude/uapi/@ &&
5899		    $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) {
5900			WARN("PREFER_ALIGNED",
5901			     "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr);
5902		}
5903
5904# Check for __attribute__ section, prefer __section
5905		if ($realfile !~ m@\binclude/uapi/@ &&
5906		    $line =~ /\b__attribute__\s*\(\s*\(.*_*section_*\s*\(\s*("[^"]*")/) {
5907			my $old = substr($rawline, $-[1], $+[1] - $-[1]);
5908			my $new = substr($old, 1, -1);
5909			if (WARN("PREFER_SECTION",
5910				 "__section($new) is preferred over __attribute__((section($old)))\n" . $herecurr) &&
5911			    $fix) {
5912				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*_*section_*\s*\(\s*\Q$old\E\s*\)\s*\)\s*\)/__section($new)/;
5913			}
5914		}
5915
5916# Check for __attribute__ format(printf, prefer __printf
5917		if ($realfile !~ m@\binclude/uapi/@ &&
5918		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) {
5919			if (WARN("PREFER_PRINTF",
5920				 "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) &&
5921			    $fix) {
5922				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex;
5923
5924			}
5925		}
5926
5927# Check for __attribute__ format(scanf, prefer __scanf
5928		if ($realfile !~ m@\binclude/uapi/@ &&
5929		    $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) {
5930			if (WARN("PREFER_SCANF",
5931				 "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) &&
5932			    $fix) {
5933				$fixed[$fixlinenr] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex;
5934			}
5935		}
5936
5937# Check for __attribute__ weak, or __weak declarations (may have link issues)
5938		if ($perl_version_ok &&
5939		    $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
5940		    ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
5941		     $line =~ /\b__weak\b/)) {
5942			ERROR("WEAK_DECLARATION",
5943			      "Using weak declarations can have unintended link defects\n" . $herecurr);
5944		}
5945
5946# check for c99 types like uint8_t used outside of uapi/ and tools/
5947		if ($realfile !~ m@\binclude/uapi/@ &&
5948		    $realfile !~ m@\btools/@ &&
5949		    $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
5950			my $type = $1;
5951			if ($type =~ /\b($typeC99Typedefs)\b/) {
5952				$type = $1;
5953				my $kernel_type = 'u';
5954				$kernel_type = 's' if ($type =~ /^_*[si]/);
5955				$type =~ /(\d+)/;
5956				$kernel_type .= $1;
5957				if (CHK("PREFER_KERNEL_TYPES",
5958					"Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
5959				    $fix) {
5960					$fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
5961				}
5962			}
5963		}
5964
5965# check for cast of C90 native int or longer types constants
5966		if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
5967			my $cast = $1;
5968			my $const = $2;
5969			if (WARN("TYPECAST_INT_CONSTANT",
5970				 "Unnecessary typecast of c90 int constant\n" . $herecurr) &&
5971			    $fix) {
5972				my $suffix = "";
5973				my $newconst = $const;
5974				$newconst =~ s/${Int_type}$//;
5975				$suffix .= 'U' if ($cast =~ /\bunsigned\b/);
5976				if ($cast =~ /\blong\s+long\b/) {
5977					$suffix .= 'LL';
5978				} elsif ($cast =~ /\blong\b/) {
5979					$suffix .= 'L';
5980				}
5981				$fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
5982			}
5983		}
5984
5985# check for sizeof(&)
5986		if ($line =~ /\bsizeof\s*\(\s*\&/) {
5987			WARN("SIZEOF_ADDRESS",
5988			     "sizeof(& should be avoided\n" . $herecurr);
5989		}
5990
5991# check for sizeof without parenthesis
5992		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
5993			if (WARN("SIZEOF_PARENTHESIS",
5994				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
5995			    $fix) {
5996				$fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
5997			}
5998		}
5999
6000# check for struct spinlock declarations
6001		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6002			WARN("USE_SPINLOCK_T",
6003			     "struct spinlock should be spinlock_t\n" . $herecurr);
6004		}
6005
6006# check for seq_printf uses that could be seq_puts
6007		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6008			my $fmt = get_quoted_string($line, $rawline);
6009			$fmt =~ s/%%//g;
6010			if ($fmt !~ /%/) {
6011				if (WARN("PREFER_SEQ_PUTS",
6012					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6013				    $fix) {
6014					$fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6015				}
6016			}
6017		}
6018
6019# check for vsprintf extension %p<foo> misuses
6020		if ($perl_version_ok &&
6021		    defined $stat &&
6022		    $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6023		    $1 !~ /^_*volatile_*$/) {
6024			my $stat_real;
6025
6026			my $lc = $stat =~ tr@\n@@;
6027			$lc = $lc + $linenr;
6028		        for (my $count = $linenr; $count <= $lc; $count++) {
6029				my $specifier;
6030				my $extension;
6031				my $qualifier;
6032				my $bad_specifier = "";
6033				my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6034				$fmt =~ s/%%//g;
6035
6036				while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6037					$specifier = $1;
6038					$extension = $2;
6039					$qualifier = $3;
6040					if ($extension !~ /[SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6041					    ($extension eq "f" &&
6042					     defined $qualifier && $qualifier !~ /^w/)) {
6043						$bad_specifier = $specifier;
6044						last;
6045					}
6046					if ($extension eq "x" && !defined($stat_real)) {
6047						if (!defined($stat_real)) {
6048							$stat_real = get_stat_real($linenr, $lc);
6049						}
6050						WARN("VSPRINTF_SPECIFIER_PX",
6051						     "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");
6052					}
6053				}
6054				if ($bad_specifier ne "") {
6055					my $stat_real = get_stat_real($linenr, $lc);
6056					my $ext_type = "Invalid";
6057					my $use = "";
6058					if ($bad_specifier =~ /p[Ff]/) {
6059						$use = " - use %pS instead";
6060						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6061					}
6062
6063					WARN("VSPRINTF_POINTER_EXTENSION",
6064					     "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6065				}
6066			}
6067		}
6068
6069# Check for misused memsets
6070		if ($perl_version_ok &&
6071		    defined $stat &&
6072		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6073
6074			my $ms_addr = $2;
6075			my $ms_val = $7;
6076			my $ms_size = $12;
6077
6078			if ($ms_size =~ /^(0x|)0$/i) {
6079				ERROR("MEMSET",
6080				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6081			} elsif ($ms_size =~ /^(0x|)1$/i) {
6082				WARN("MEMSET",
6083				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
6084			}
6085		}
6086
6087# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
6088#		if ($perl_version_ok &&
6089#		    defined $stat &&
6090#		    $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6091#			if (WARN("PREFER_ETHER_ADDR_COPY",
6092#				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
6093#			    $fix) {
6094#				$fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
6095#			}
6096#		}
6097
6098# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
6099#		if ($perl_version_ok &&
6100#		    defined $stat &&
6101#		    $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6102#			WARN("PREFER_ETHER_ADDR_EQUAL",
6103#			     "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
6104#		}
6105
6106# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
6107# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
6108#		if ($perl_version_ok &&
6109#		    defined $stat &&
6110#		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
6111#
6112#			my $ms_val = $7;
6113#
6114#			if ($ms_val =~ /^(?:0x|)0+$/i) {
6115#				if (WARN("PREFER_ETH_ZERO_ADDR",
6116#					 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
6117#				    $fix) {
6118#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
6119#				}
6120#			} elsif ($ms_val =~ /^(?:0xff|255)$/i) {
6121#				if (WARN("PREFER_ETH_BROADCAST_ADDR",
6122#					 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
6123#				    $fix) {
6124#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
6125#				}
6126#			}
6127#		}
6128
6129# typecasts on min/max could be min_t/max_t
6130		if ($perl_version_ok &&
6131		    defined $stat &&
6132		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
6133			if (defined $2 || defined $7) {
6134				my $call = $1;
6135				my $cast1 = deparenthesize($2);
6136				my $arg1 = $3;
6137				my $cast2 = deparenthesize($7);
6138				my $arg2 = $8;
6139				my $cast;
6140
6141				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
6142					$cast = "$cast1 or $cast2";
6143				} elsif ($cast1 ne "") {
6144					$cast = $cast1;
6145				} else {
6146					$cast = $cast2;
6147				}
6148				WARN("MINMAX",
6149				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
6150			}
6151		}
6152
6153# check usleep_range arguments
6154		if ($perl_version_ok &&
6155		    defined $stat &&
6156		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
6157			my $min = $1;
6158			my $max = $7;
6159			if ($min eq $max) {
6160				WARN("USLEEP_RANGE",
6161				     "usleep_range should not use min == max args; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6162			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
6163				 $min > $max) {
6164				WARN("USLEEP_RANGE",
6165				     "usleep_range args reversed, use min then max; see Documentation/timers/timers-howto.rst\n" . "$here\n$stat\n");
6166			}
6167		}
6168
6169# check for naked sscanf
6170		if ($perl_version_ok &&
6171		    defined $stat &&
6172		    $line =~ /\bsscanf\b/ &&
6173		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
6174		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
6175		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
6176			my $lc = $stat =~ tr@\n@@;
6177			$lc = $lc + $linenr;
6178			my $stat_real = get_stat_real($linenr, $lc);
6179			WARN("NAKED_SSCANF",
6180			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
6181		}
6182
6183# check for simple sscanf that should be kstrto<foo>
6184		if ($perl_version_ok &&
6185		    defined $stat &&
6186		    $line =~ /\bsscanf\b/) {
6187			my $lc = $stat =~ tr@\n@@;
6188			$lc = $lc + $linenr;
6189			my $stat_real = get_stat_real($linenr, $lc);
6190			if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
6191				my $format = $6;
6192				my $count = $format =~ tr@%@%@;
6193				if ($count == 1 &&
6194				    $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
6195					WARN("SSCANF_TO_KSTRTO",
6196					     "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
6197				}
6198			}
6199		}
6200
6201# check for new externs in .h files.
6202		if ($realfile =~ /\.h$/ &&
6203		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
6204			if (CHK("AVOID_EXTERNS",
6205				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
6206			    $fix) {
6207				$fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
6208			}
6209		}
6210
6211# check for new externs in .c files.
6212		if ($realfile =~ /\.c$/ && defined $stat &&
6213		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
6214		{
6215			my $function_name = $1;
6216			my $paren_space = $2;
6217
6218			my $s = $stat;
6219			if (defined $cond) {
6220				substr($s, 0, length($cond), '');
6221			}
6222			if ($s =~ /^\s*;/ &&
6223			    $function_name ne 'uninitialized_var')
6224			{
6225				WARN("AVOID_EXTERNS",
6226				     "externs should be avoided in .c files\n" .  $herecurr);
6227			}
6228
6229			if ($paren_space =~ /\n/) {
6230				WARN("FUNCTION_ARGUMENTS",
6231				     "arguments for function declarations should follow identifier\n" . $herecurr);
6232			}
6233
6234		} elsif ($realfile =~ /\.c$/ && defined $stat &&
6235		    $stat =~ /^.\s*extern\s+/)
6236		{
6237			WARN("AVOID_EXTERNS",
6238			     "externs should be avoided in .c files\n" .  $herecurr);
6239		}
6240
6241# check for function declarations that have arguments without identifier names
6242		if (defined $stat &&
6243		    $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
6244		    $1 ne "void") {
6245			my $args = trim($1);
6246			while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
6247				my $arg = trim($1);
6248				if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
6249					WARN("FUNCTION_ARGUMENTS",
6250					     "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
6251				}
6252			}
6253		}
6254
6255# check for function definitions
6256		if ($perl_version_ok &&
6257		    defined $stat &&
6258		    $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
6259			$context_function = $1;
6260
6261# check for multiline function definition with misplaced open brace
6262			my $ok = 0;
6263			my $cnt = statement_rawlines($stat);
6264			my $herectx = $here . "\n";
6265			for (my $n = 0; $n < $cnt; $n++) {
6266				my $rl = raw_line($linenr, $n);
6267				$herectx .=  $rl . "\n";
6268				$ok = 1 if ($rl =~ /^[ \+]\{/);
6269				$ok = 1 if ($rl =~ /\{/ && $n == 0);
6270				last if $rl =~ /^[ \+].*\{/;
6271			}
6272			if (!$ok) {
6273				ERROR("OPEN_BRACE",
6274				      "open brace '{' following function definitions go on the next line\n" . $herectx);
6275			}
6276		}
6277
6278# checks for new __setup's
6279		if ($rawline =~ /\b__setup\("([^"]*)"/) {
6280			my $name = $1;
6281
6282			if (!grep(/$name/, @setup_docs)) {
6283				CHK("UNDOCUMENTED_SETUP",
6284				    "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.rst\n" . $herecurr);
6285			}
6286		}
6287
6288# check for pointless casting of alloc functions
6289		if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
6290			WARN("UNNECESSARY_CASTS",
6291			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
6292		}
6293
6294# alloc style
6295# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
6296		if ($perl_version_ok &&
6297		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
6298			CHK("ALLOC_SIZEOF_STRUCT",
6299			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
6300		}
6301
6302# check for k[mz]alloc with multiplies that could be kmalloc_array/kcalloc
6303		if ($perl_version_ok &&
6304		    defined $stat &&
6305		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*(k[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
6306			my $oldfunc = $3;
6307			my $a1 = $4;
6308			my $a2 = $10;
6309			my $newfunc = "kmalloc_array";
6310			$newfunc = "kcalloc" if ($oldfunc eq "kzalloc");
6311			my $r1 = $a1;
6312			my $r2 = $a2;
6313			if ($a1 =~ /^sizeof\s*\S/) {
6314				$r1 = $a2;
6315				$r2 = $a1;
6316			}
6317			if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
6318			    !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
6319				my $cnt = statement_rawlines($stat);
6320				my $herectx = get_stat_here($linenr, $cnt, $here);
6321
6322				if (WARN("ALLOC_WITH_MULTIPLY",
6323					 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
6324				    $cnt == 1 &&
6325				    $fix) {
6326					$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;
6327				}
6328			}
6329		}
6330
6331# check for krealloc arg reuse
6332		if ($perl_version_ok &&
6333		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
6334		    $1 eq $3) {
6335			WARN("KREALLOC_ARG_REUSE",
6336			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
6337		}
6338
6339# check for alloc argument mismatch
6340		if ($line =~ /\b(kcalloc|kmalloc_array)\s*\(\s*sizeof\b/) {
6341			WARN("ALLOC_ARRAY_ARGS",
6342			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
6343		}
6344
6345# check for multiple semicolons
6346		if ($line =~ /;\s*;\s*$/) {
6347			if (WARN("ONE_SEMICOLON",
6348				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
6349			    $fix) {
6350				$fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
6351			}
6352		}
6353
6354# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
6355		if ($realfile !~ m@^include/uapi/@ &&
6356		    $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
6357			my $ull = "";
6358			$ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
6359			if (CHK("BIT_MACRO",
6360				"Prefer using the BIT$ull macro\n" . $herecurr) &&
6361			    $fix) {
6362				$fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
6363			}
6364		}
6365
6366# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
6367		if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(CONFIG_[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
6368			my $config = $1;
6369			if (WARN("PREFER_IS_ENABLED",
6370				 "Prefer IS_ENABLED(<FOO>) to CONFIG_<FOO> || CONFIG_<FOO>_MODULE\n" . $herecurr) &&
6371			    $fix) {
6372				$fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
6373			}
6374		}
6375
6376# check for case / default statements not preceded by break/fallthrough/switch
6377		if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) {
6378			my $has_break = 0;
6379			my $has_statement = 0;
6380			my $count = 0;
6381			my $prevline = $linenr;
6382			while ($prevline > 1 && ($file || $count < 3) && !$has_break) {
6383				$prevline--;
6384				my $rline = $rawlines[$prevline - 1];
6385				my $fline = $lines[$prevline - 1];
6386				last if ($fline =~ /^\@\@/);
6387				next if ($fline =~ /^\-/);
6388				next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/);
6389				$has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i);
6390				next if ($fline =~ /^.[\s$;]*$/);
6391				$has_statement = 1;
6392				$count++;
6393				$has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|exit\s*\(\b|return\b|goto\b|continue\b)/);
6394			}
6395			if (!$has_break && $has_statement) {
6396				WARN("MISSING_BREAK",
6397				     "Possible switch case/default not preceded by break or fallthrough comment\n" . $herecurr);
6398			}
6399		}
6400
6401# check for switch/default statements without a break;
6402		if ($perl_version_ok &&
6403		    defined $stat &&
6404		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
6405			my $cnt = statement_rawlines($stat);
6406			my $herectx = get_stat_here($linenr, $cnt, $here);
6407
6408			WARN("DEFAULT_NO_BREAK",
6409			     "switch default: should use break\n" . $herectx);
6410		}
6411
6412# check for gcc specific __FUNCTION__
6413		if ($line =~ /\b__FUNCTION__\b/) {
6414			if (WARN("USE_FUNC",
6415				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
6416			    $fix) {
6417				$fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
6418			}
6419		}
6420
6421# check for uses of __DATE__, __TIME__, __TIMESTAMP__
6422		while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
6423			ERROR("DATE_TIME",
6424			      "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
6425		}
6426
6427# check for use of yield()
6428		if ($line =~ /\byield\s*\(\s*\)/) {
6429			WARN("YIELD",
6430			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
6431		}
6432
6433# check for comparisons against true and false
6434		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
6435			my $lead = $1;
6436			my $arg = $2;
6437			my $test = $3;
6438			my $otype = $4;
6439			my $trail = $5;
6440			my $op = "!";
6441
6442			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
6443
6444			my $type = lc($otype);
6445			if ($type =~ /^(?:true|false)$/) {
6446				if (("$test" eq "==" && "$type" eq "true") ||
6447				    ("$test" eq "!=" && "$type" eq "false")) {
6448					$op = "";
6449				}
6450
6451				CHK("BOOL_COMPARISON",
6452				    "Using comparison to $otype is error prone\n" . $herecurr);
6453
6454## maybe suggesting a correct construct would better
6455##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
6456
6457			}
6458		}
6459
6460# check for semaphores initialized locked
6461		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
6462			WARN("CONSIDER_COMPLETION",
6463			     "consider using a completion\n" . $herecurr);
6464		}
6465
6466# recommend kstrto* over simple_strto* and strict_strto*
6467		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
6468			WARN("CONSIDER_KSTRTO",
6469			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
6470		}
6471
6472# check for __initcall(), use device_initcall() explicitly or more appropriate function please
6473		if ($line =~ /^.\s*__initcall\s*\(/) {
6474			WARN("USE_DEVICE_INITCALL",
6475			     "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
6476		}
6477
6478# check for spin_is_locked(), suggest lockdep instead
6479		if ($line =~ /\bspin_is_locked\(/) {
6480			WARN("USE_LOCKDEP",
6481			     "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
6482		}
6483
6484# check for deprecated apis
6485		if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
6486			my $deprecated_api = $1;
6487			my $new_api = $deprecated_apis{$deprecated_api};
6488			WARN("DEPRECATED_API",
6489			     "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
6490		}
6491
6492# check for various structs that are normally const (ops, kgdb, device_tree)
6493# and avoid what seem like struct definitions 'struct foo {'
6494		if ($line !~ /\bconst\b/ &&
6495		    $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
6496			WARN("CONST_STRUCT",
6497			     "struct $1 should normally be const\n" . $herecurr);
6498		}
6499
6500# use of NR_CPUS is usually wrong
6501# ignore definitions of NR_CPUS and usage to define arrays as likely right
6502		if ($line =~ /\bNR_CPUS\b/ &&
6503		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
6504		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
6505		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
6506		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
6507		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/)
6508		{
6509			WARN("NR_CPUS",
6510			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
6511		}
6512
6513# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
6514		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
6515			ERROR("DEFINE_ARCH_HAS",
6516			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
6517		}
6518
6519# likely/unlikely comparisons similar to "(likely(foo) > 0)"
6520		if ($perl_version_ok &&
6521		    $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
6522			WARN("LIKELY_MISUSE",
6523			     "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
6524		}
6525
6526# nested likely/unlikely calls
6527		if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
6528			WARN("LIKELY_MISUSE",
6529			     "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
6530		}
6531
6532# whine mightly about in_atomic
6533		if ($line =~ /\bin_atomic\s*\(/) {
6534			if ($realfile =~ m@^drivers/@) {
6535				ERROR("IN_ATOMIC",
6536				      "do not use in_atomic in drivers\n" . $herecurr);
6537			} elsif ($realfile !~ m@^kernel/@) {
6538				WARN("IN_ATOMIC",
6539				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
6540			}
6541		}
6542
6543# check for mutex_trylock_recursive usage
6544		if ($line =~ /mutex_trylock_recursive/) {
6545			ERROR("LOCKING",
6546			      "recursive locking is bad, do not use this ever.\n" . $herecurr);
6547		}
6548
6549# check for lockdep_set_novalidate_class
6550		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
6551		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
6552			if ($realfile !~ m@^kernel/lockdep@ &&
6553			    $realfile !~ m@^include/linux/lockdep@ &&
6554			    $realfile !~ m@^drivers/base/core@) {
6555				ERROR("LOCKDEP",
6556				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
6557			}
6558		}
6559
6560		if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
6561		    $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
6562			WARN("EXPORTED_WORLD_WRITABLE",
6563			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
6564		}
6565
6566# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
6567# and whether or not function naming is typical and if
6568# DEVICE_ATTR permissions uses are unusual too
6569		if ($perl_version_ok &&
6570		    defined $stat &&
6571		    $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*\)/) {
6572			my $var = $1;
6573			my $perms = $2;
6574			my $show = $3;
6575			my $store = $4;
6576			my $octal_perms = perms_to_octal($perms);
6577			if ($show =~ /^${var}_show$/ &&
6578			    $store =~ /^${var}_store$/ &&
6579			    $octal_perms eq "0644") {
6580				if (WARN("DEVICE_ATTR_RW",
6581					 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
6582				    $fix) {
6583					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
6584				}
6585			} elsif ($show =~ /^${var}_show$/ &&
6586				 $store =~ /^NULL$/ &&
6587				 $octal_perms eq "0444") {
6588				if (WARN("DEVICE_ATTR_RO",
6589					 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
6590				    $fix) {
6591					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
6592				}
6593			} elsif ($show =~ /^NULL$/ &&
6594				 $store =~ /^${var}_store$/ &&
6595				 $octal_perms eq "0200") {
6596				if (WARN("DEVICE_ATTR_WO",
6597					 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
6598				    $fix) {
6599					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
6600				}
6601			} elsif ($octal_perms eq "0644" ||
6602				 $octal_perms eq "0444" ||
6603				 $octal_perms eq "0200") {
6604				my $newshow = "$show";
6605				$newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
6606				my $newstore = $store;
6607				$newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
6608				my $rename = "";
6609				if ($show ne $newshow) {
6610					$rename .= " '$show' to '$newshow'";
6611				}
6612				if ($store ne $newstore) {
6613					$rename .= " '$store' to '$newstore'";
6614				}
6615				WARN("DEVICE_ATTR_FUNCTIONS",
6616				     "Consider renaming function(s)$rename\n" . $herecurr);
6617			} else {
6618				WARN("DEVICE_ATTR_PERMS",
6619				     "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
6620			}
6621		}
6622
6623# Mode permission misuses where it seems decimal should be octal
6624# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
6625# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
6626#   specific definition of not visible in sysfs.
6627# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
6628#   use the default permissions
6629		if ($perl_version_ok &&
6630		    defined $stat &&
6631		    $line =~ /$mode_perms_search/) {
6632			foreach my $entry (@mode_permission_funcs) {
6633				my $func = $entry->[0];
6634				my $arg_pos = $entry->[1];
6635
6636				my $lc = $stat =~ tr@\n@@;
6637				$lc = $lc + $linenr;
6638				my $stat_real = get_stat_real($linenr, $lc);
6639
6640				my $skip_args = "";
6641				if ($arg_pos > 1) {
6642					$arg_pos--;
6643					$skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
6644				}
6645				my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
6646				if ($stat =~ /$test/) {
6647					my $val = $1;
6648					$val = $6 if ($skip_args ne "");
6649					if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
6650					    (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
6651					     ($val =~ /^$Octal$/ && length($val) ne 4))) {
6652						ERROR("NON_OCTAL_PERMISSIONS",
6653						      "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
6654					}
6655					if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
6656						ERROR("EXPORTED_WORLD_WRITABLE",
6657						      "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
6658					}
6659				}
6660			}
6661		}
6662
6663# check for uses of S_<PERMS> that could be octal for readability
6664		while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
6665			my $oval = $1;
6666			my $octal = perms_to_octal($oval);
6667			if (WARN("SYMBOLIC_PERMS",
6668				 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
6669			    $fix) {
6670				$fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
6671			}
6672		}
6673
6674# validate content of MODULE_LICENSE against list from include/linux/module.h
6675		if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
6676			my $extracted_string = get_quoted_string($line, $rawline);
6677			my $valid_licenses = qr{
6678						GPL|
6679						GPL\ v2|
6680						GPL\ and\ additional\ rights|
6681						Dual\ BSD/GPL|
6682						Dual\ MIT/GPL|
6683						Dual\ MPL/GPL|
6684						Proprietary
6685					}x;
6686			if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
6687				WARN("MODULE_LICENSE",
6688				     "unknown module license " . $extracted_string . "\n" . $herecurr);
6689			}
6690		}
6691
6692# check for sysctl duplicate constants
6693		if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
6694			WARN("DUPLICATED_SYSCTL_CONST",
6695				"duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
6696		}
6697	}
6698
6699	# If we have no input at all, then there is nothing to report on
6700	# so just keep quiet.
6701	if ($#rawlines == -1) {
6702		exit(0);
6703	}
6704
6705	# In mailback mode only produce a report in the negative, for
6706	# things that appear to be patches.
6707	if ($mailback && ($clean == 1 || !$is_patch)) {
6708		exit(0);
6709	}
6710
6711	# This is not a patch, and we are are in 'no-patch' mode so
6712	# just keep quiet.
6713	if (!$chk_patch && !$is_patch) {
6714		exit(0);
6715	}
6716
6717	if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
6718		ERROR("NOT_UNIFIED_DIFF",
6719		      "Does not appear to be a unified-diff format patch\n");
6720	}
6721	if ($is_patch && $has_commit_log && $chk_signoff) {
6722		if ($signoff == 0) {
6723			ERROR("MISSING_SIGN_OFF",
6724			      "Missing Signed-off-by: line(s)\n");
6725		} elsif (!$authorsignoff) {
6726			WARN("NO_AUTHOR_SIGN_OFF",
6727			     "Missing Signed-off-by: line by nominal patch author '$author'\n");
6728		}
6729	}
6730
6731	print report_dump();
6732	if ($summary && !($clean == 1 && $quiet == 1)) {
6733		print "$filename " if ($summary_file);
6734		print "total: $cnt_error errors, $cnt_warn warnings, " .
6735			(($check)? "$cnt_chk checks, " : "") .
6736			"$cnt_lines lines checked\n";
6737	}
6738
6739	if ($quiet == 0) {
6740		# If there were any defects found and not already fixing them
6741		if (!$clean and !$fix) {
6742			print << "EOM"
6743
6744NOTE: For some of the reported defects, checkpatch may be able to
6745      mechanically convert to the typical style using --fix or --fix-inplace.
6746EOM
6747		}
6748		# If there were whitespace errors which cleanpatch can fix
6749		# then suggest that.
6750		if ($rpt_cleaners) {
6751			$rpt_cleaners = 0;
6752			print << "EOM"
6753
6754NOTE: Whitespace errors detected.
6755      You may wish to use scripts/cleanpatch or scripts/cleanfile
6756EOM
6757		}
6758	}
6759
6760	if ($clean == 0 && $fix &&
6761	    ("@rawlines" ne "@fixed" ||
6762	     $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
6763		my $newfile = $filename;
6764		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
6765		my $linecount = 0;
6766		my $f;
6767
6768		@fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
6769
6770		open($f, '>', $newfile)
6771		    or die "$P: Can't open $newfile for write\n";
6772		foreach my $fixed_line (@fixed) {
6773			$linecount++;
6774			if ($file) {
6775				if ($linecount > 3) {
6776					$fixed_line =~ s/^\+//;
6777					print $f $fixed_line . "\n";
6778				}
6779			} else {
6780				print $f $fixed_line . "\n";
6781			}
6782		}
6783		close($f);
6784
6785		if (!$quiet) {
6786			print << "EOM";
6787
6788Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
6789
6790Do _NOT_ trust the results written to this file.
6791Do _NOT_ submit these changes without inspecting them for correctness.
6792
6793This EXPERIMENTAL file is simply a convenience to help rewrite patches.
6794No warranties, expressed or implied...
6795EOM
6796		}
6797	}
6798
6799	if ($quiet == 0) {
6800		print "\n";
6801		if ($clean == 1) {
6802			print "$vname has no obvious style problems and is ready for submission.\n";
6803		} else {
6804			print "$vname has style problems, please review.\n";
6805		}
6806	}
6807	return $clean;
6808}
6809