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