xref: /linux/scripts/checkpatch.pl (revision 37a93dd5c49b5fda807fd204edf2547c3493319c)
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 patch separator
3037		if ($line =~ /^---$/) {
3038			$has_patch_separator = 1;
3039			$in_commit_log = 0;
3040		}
3041
3042# Check if MAINTAINERS is being updated.  If so, there's probably no need to
3043# emit the "does MAINTAINERS need updating?" message on file add/move/delete
3044		if ($line =~ /^\s*MAINTAINERS\s*\|/) {
3045			$reported_maintainer_file = 1;
3046		}
3047
3048# Check signature styles
3049		if (!$in_header_lines &&
3050		    $line =~ /^(\s*)([a-z0-9_-]+by:|$signature_tags)(\s*)(.*)/i) {
3051			my $space_before = $1;
3052			my $sign_off = $2;
3053			my $space_after = $3;
3054			my $email = $4;
3055			my $ucfirst_sign_off = ucfirst(lc($sign_off));
3056
3057			if ($sign_off !~ /$signature_tags/) {
3058				my $suggested_signature = find_standard_signature($sign_off);
3059				if ($suggested_signature eq "") {
3060					WARN("BAD_SIGN_OFF",
3061					     "Non-standard signature: $sign_off\n" . $herecurr);
3062				} else {
3063					if (WARN("BAD_SIGN_OFF",
3064						 "Non-standard signature: '$sign_off' - perhaps '$suggested_signature'?\n" . $herecurr) &&
3065					    $fix) {
3066						$fixed[$fixlinenr] =~ s/$sign_off/$suggested_signature/;
3067					}
3068				}
3069			}
3070			if (defined $space_before && $space_before ne "") {
3071				if (WARN("BAD_SIGN_OFF",
3072					 "Do not use whitespace before $ucfirst_sign_off\n" . $herecurr) &&
3073				    $fix) {
3074					$fixed[$fixlinenr] =
3075					    "$ucfirst_sign_off $email";
3076				}
3077			}
3078			if ($sign_off =~ /-by:$/i && $sign_off ne $ucfirst_sign_off) {
3079				if (WARN("BAD_SIGN_OFF",
3080					 "'$ucfirst_sign_off' is the preferred signature form\n" . $herecurr) &&
3081				    $fix) {
3082					$fixed[$fixlinenr] =
3083					    "$ucfirst_sign_off $email";
3084				}
3085
3086			}
3087			if (!defined $space_after || $space_after ne " ") {
3088				if (WARN("BAD_SIGN_OFF",
3089					 "Use a single space after $ucfirst_sign_off\n" . $herecurr) &&
3090				    $fix) {
3091					$fixed[$fixlinenr] =
3092					    "$ucfirst_sign_off $email";
3093				}
3094			}
3095
3096			my ($email_name, $name_comment, $email_address, $comment) = parse_email($email);
3097			my $suggested_email = format_email(($email_name, $name_comment, $email_address, $comment));
3098			if ($suggested_email eq "") {
3099				ERROR("BAD_SIGN_OFF",
3100				      "Unrecognized email address: '$email'\n" . $herecurr);
3101			} else {
3102				my $dequoted = $suggested_email;
3103				$dequoted =~ s/^"//;
3104				$dequoted =~ s/" </ </;
3105				# Don't force email to have quotes
3106				# Allow just an angle bracketed address
3107				if (!same_email_addresses($email, $suggested_email)) {
3108					if (WARN("BAD_SIGN_OFF",
3109						 "email address '$email' might be better as '$suggested_email'\n" . $herecurr) &&
3110					    $fix) {
3111						$fixed[$fixlinenr] =~ s/\Q$email\E/$suggested_email/;
3112					}
3113				}
3114
3115				# Address part shouldn't have comments
3116				my $stripped_address = $email_address;
3117				$stripped_address =~ s/\([^\(\)]*\)//g;
3118				if ($email_address ne $stripped_address) {
3119					if (WARN("BAD_SIGN_OFF",
3120						 "address part of email should not have comments: '$email_address'\n" . $herecurr) &&
3121					    $fix) {
3122						$fixed[$fixlinenr] =~ s/\Q$email_address\E/$stripped_address/;
3123					}
3124				}
3125
3126				# Only one name comment should be allowed
3127				my $comment_count = () = $name_comment =~ /\([^\)]+\)/g;
3128				if ($comment_count > 1) {
3129					WARN("BAD_SIGN_OFF",
3130					     "Use a single name comment in email: '$email'\n" . $herecurr);
3131				}
3132
3133
3134				# stable@vger.kernel.org or stable@kernel.org shouldn't
3135				# have an email name. In addition comments should strictly
3136				# begin with a #
3137				if ($email =~ /^.*stable\@(?:vger\.)?kernel\.org/i) {
3138					if (($comment ne "" && $comment !~ /^#.+/) ||
3139					    ($email_name ne "")) {
3140						my $cur_name = $email_name;
3141						my $new_comment = $comment;
3142						$cur_name =~ s/[a-zA-Z\s\-\"]+//g;
3143
3144						# Remove brackets enclosing comment text
3145						# and # from start of comments to get comment text
3146						$new_comment =~ s/^\((.*)\)$/$1/;
3147						$new_comment =~ s/^\[(.*)\]$/$1/;
3148						$new_comment =~ s/^[\s\#]+|\s+$//g;
3149
3150						$new_comment = trim("$new_comment $cur_name") if ($cur_name ne $new_comment);
3151						$new_comment = " # $new_comment" if ($new_comment ne "");
3152						my $new_email = "$email_address$new_comment";
3153
3154						if (WARN("BAD_STABLE_ADDRESS_STYLE",
3155							 "Invalid email format for stable: '$email', prefer '$new_email'\n" . $herecurr) &&
3156						    $fix) {
3157							$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3158						}
3159					}
3160				} elsif ($comment ne "" && $comment !~ /^(?:#.+|\(.+\))$/) {
3161					my $new_comment = $comment;
3162
3163					# Extract comment text from within brackets or
3164					# c89 style /*...*/ comments
3165					$new_comment =~ s/^\[(.*)\]$/$1/;
3166					$new_comment =~ s/^\/\*(.*)\*\/$/$1/;
3167
3168					$new_comment = trim($new_comment);
3169					$new_comment =~ s/^[^\w]$//; # Single lettered comment with non word character is usually a typo
3170					$new_comment = "($new_comment)" if ($new_comment ne "");
3171					my $new_email = format_email($email_name, $name_comment, $email_address, $new_comment);
3172
3173					if (WARN("BAD_SIGN_OFF",
3174						 "Unexpected content after email: '$email', should be: '$new_email'\n" . $herecurr) &&
3175					    $fix) {
3176						$fixed[$fixlinenr] =~ s/\Q$email\E/$new_email/;
3177					}
3178				}
3179			}
3180
3181# Check for duplicate signatures
3182			my $sig_nospace = $line;
3183			$sig_nospace =~ s/\s//g;
3184			$sig_nospace = lc($sig_nospace);
3185			if (defined $signatures{$sig_nospace}) {
3186				WARN("BAD_SIGN_OFF",
3187				     "Duplicate signature\n" . $herecurr);
3188			} else {
3189				$signatures{$sig_nospace} = 1;
3190			}
3191
3192# Check Co-developed-by: immediately followed by Signed-off-by: with same name and email
3193			if ($sign_off =~ /^co-developed-by:$/i) {
3194				if ($email eq $author) {
3195					WARN("BAD_SIGN_OFF",
3196					      "Co-developed-by: should not be used to attribute nominal patch author '$author'\n" . $herecurr);
3197				}
3198				if (!defined $lines[$linenr]) {
3199					WARN("BAD_SIGN_OFF",
3200					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr);
3201				} elsif ($rawlines[$linenr] !~ /^signed-off-by:\s*(.*)/i) {
3202					WARN("BAD_SIGN_OFF",
3203					     "Co-developed-by: must be immediately followed by Signed-off-by:\n" . $herecurr . $rawlines[$linenr] . "\n");
3204				} elsif ($1 ne $email) {
3205					WARN("BAD_SIGN_OFF",
3206					     "Co-developed-by and Signed-off-by: name/email do not match\n" . $herecurr . $rawlines[$linenr] . "\n");
3207				}
3208			}
3209
3210# check if Reported-by: is followed by a Closes: tag
3211			if ($sign_off =~ /^reported(?:|-and-tested)-by:$/i) {
3212				if (!defined $lines[$linenr]) {
3213					WARN("BAD_REPORTED_BY_LINK",
3214					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . "\n");
3215				} elsif ($rawlines[$linenr] !~ /^closes:\s*/i) {
3216					WARN("BAD_REPORTED_BY_LINK",
3217					     "Reported-by: should be immediately followed by Closes: with a URL to the report\n" . $herecurr . $rawlines[$linenr] . "\n");
3218				}
3219			}
3220		}
3221
3222# These indicate a bug fix
3223		if (!$in_header_lines && !$is_patch &&
3224			$line =~ /^This reverts commit/) {
3225			$is_revert = 1;
3226		}
3227
3228		if (!$in_header_lines && !$is_patch &&
3229		    $line =~ /((?:(?:BUG: K.|UB)SAN: |Call Trace:|stable\@|syzkaller))/) {
3230			$needs_fixes_tag = $1;
3231		}
3232
3233# Check Fixes: styles is correct
3234		if (!$in_header_lines &&
3235		    $line =~ /^\s*(fixes:?)\s*(?:commit\s*)?([0-9a-f]{5,40})(?:\s*($balanced_parens))?/i) {
3236			my $tag = $1;
3237			my $orig_commit = $2;
3238			my $title;
3239			my $title_has_quotes = 0;
3240			$fixes_tag = 1;
3241			if (defined $3) {
3242				# Always strip leading/trailing parens then double quotes if existing
3243				$title = substr($3, 1, -1);
3244				if ($title =~ /^".*"$/) {
3245					$title = substr($title, 1, -1);
3246					$title_has_quotes = 1;
3247				}
3248			} else {
3249				$title = "commit title"
3250			}
3251
3252
3253			my $tag_case = not ($tag eq "Fixes:");
3254			my $tag_space = not ($line =~ /^fixes:? [0-9a-f]{5,40} ($balanced_parens)/i);
3255
3256			my $id_length = not ($orig_commit =~ /^[0-9a-f]{12,40}$/i);
3257			my $id_case = not ($orig_commit !~ /[A-F]/);
3258
3259			my $id = "0123456789ab";
3260			my ($cid, $ctitle) = git_commit_info($orig_commit, $id,
3261							     $title);
3262
3263			if (defined($cid) && ($ctitle ne $title || $tag_case || $tag_space || $id_length || $id_case || !$title_has_quotes)) {
3264				my $fixed = "Fixes: $cid (\"$ctitle\")";
3265				if (WARN("BAD_FIXES_TAG",
3266				     "Please use correct Fixes: style 'Fixes: <12+ chars of sha1> (\"<title line>\")' - ie: '$fixed'\n" . $herecurr) &&
3267				    $fix) {
3268					$fixed[$fixlinenr] = $fixed;
3269				}
3270			}
3271		}
3272
3273# Check email subject for common tools that don't need to be mentioned
3274		if ($in_header_lines &&
3275		    $line =~ /^Subject:.*\b(?:checkpatch|sparse|smatch)\b[^:]/i) {
3276			WARN("EMAIL_SUBJECT",
3277			     "A patch subject line should describe the change not the tool that found it\n" . $herecurr);
3278		}
3279
3280# Check for Gerrit Change-Ids not in any patch context
3281		if ($realfile eq '' && !$has_patch_separator && $line =~ /^\s*change-id:/i) {
3282			if (ERROR("GERRIT_CHANGE_ID",
3283			          "Remove Gerrit Change-Id's before submitting upstream\n" . $herecurr) &&
3284			    $fix) {
3285				fix_delete_line($fixlinenr, $rawline);
3286			}
3287		}
3288
3289# Check if the commit log is in a possible stack dump
3290		if ($in_commit_log && !$commit_log_possible_stack_dump &&
3291		    ($line =~ /^\s*(?:WARNING:|BUG:)/ ||
3292		     $line =~ /^\s*\[\s*\d+\.\d{6,6}\s*\]/ ||
3293					# timestamp
3294		     $line =~ /^\s*\[\<[0-9a-fA-F]{8,}\>\]/) ||
3295		     $line =~ /^(?:\s+\w+:\s+[0-9a-fA-F]+){3,3}/ ||
3296		     $line =~ /^\s*\#\d+\s*\[[0-9a-fA-F]+\]\s*\w+ at [0-9a-fA-F]+/) {
3297					# stack dump address styles
3298			$commit_log_possible_stack_dump = 1;
3299		}
3300
3301# Check for line lengths > 75 in commit log, warn once
3302		if ($in_commit_log && !$commit_log_long_line &&
3303		    length($line) > 75 &&
3304		    !($line =~ /^\s*[a-zA-Z0-9_\/\.]+\s+\|\s+\d+/ ||
3305					# file delta changes
3306		      $line =~ /^\s*(?:[\w\.\-\+]*\/)++[\w\.\-\+]+:/ ||
3307					# filename then :
3308		      $line =~ /^\s*(?:Fixes:|https?:|$link_tags_search|$signature_tags)/i ||
3309					# A Fixes:, link or signature tag line
3310		      $commit_log_possible_stack_dump)) {
3311			WARN("COMMIT_LOG_LONG_LINE",
3312			     "Prefer a maximum 75 chars per line (possible unwrapped commit description?)\n" . $herecurr);
3313			$commit_log_long_line = 1;
3314		}
3315
3316# Reset possible stack dump if a blank line is found
3317		if ($in_commit_log && $commit_log_possible_stack_dump &&
3318		    $line =~ /^\s*$/) {
3319			$commit_log_possible_stack_dump = 0;
3320		}
3321
3322# Check for odd tags before a URI/URL
3323		if ($in_commit_log &&
3324		    $line =~ /^\s*(\w+:)\s*http/ && $1 !~ /^$link_tags_search$/) {
3325			if ($1 =~ /^v(?:ersion)?\d+/i) {
3326				WARN("COMMIT_LOG_VERSIONING",
3327				     "Patch version information should be after the --- line\n" . $herecurr);
3328			} else {
3329				WARN("COMMIT_LOG_USE_LINK",
3330				     "Unknown link reference '$1', use $link_tags_print instead\n" . $herecurr);
3331			}
3332		}
3333
3334# Check for misuse of the link tags
3335		if ($in_commit_log &&
3336		    $line =~ /^\s*(\w+:)\s*(\S+)/) {
3337			my $tag = $1;
3338			my $value = $2;
3339			if ($tag =~ /^$link_tags_search$/ && $value !~ m{^https?://}) {
3340				WARN("COMMIT_LOG_WRONG_LINK",
3341				     "'$tag' should be followed by a public http(s) link\n" . $herecurr);
3342			}
3343		}
3344
3345# Check for lines starting with a #
3346		if ($in_commit_log && $line =~ /^#/) {
3347			if (WARN("COMMIT_COMMENT_SYMBOL",
3348				 "Commit log lines starting with '#' are dropped by git as comments\n" . $herecurr) &&
3349			    $fix) {
3350				$fixed[$fixlinenr] =~ s/^/ /;
3351			}
3352		}
3353
3354# Check for auto-generated unhandled placeholder text (mostly for cover letters)
3355		if (($in_commit_log || $in_header_lines) &&
3356		    $rawline =~ /(?:SUBJECT|BLURB) HERE/) {
3357			ERROR("PLACEHOLDER_USE",
3358			      "Placeholder text detected\n" . $herecurr);
3359		}
3360
3361# Check for git id commit length and improperly formed commit descriptions
3362# A correctly formed commit description is:
3363#    commit <SHA-1 hash length 12+ chars> ("Complete commit subject")
3364# with the commit subject '("' prefix and '")' suffix
3365# This is a fairly compilicated block as it tests for what appears to be
3366# bare SHA-1 hash with  minimum length of 5.  It also avoids several types of
3367# possible SHA-1 matches.
3368# A commit match can span multiple lines so this block attempts to find a
3369# complete typical commit on a maximum of 3 lines
3370		if ($perl_version_ok &&
3371		    $in_commit_log && !$commit_log_possible_stack_dump &&
3372		    $line !~ /^\s*(?:Link|Patchwork|http|https|BugLink|base-commit):/i &&
3373		    $line !~ /^This reverts commit [0-9a-f]{7,40}/ &&
3374		    (($line =~ /\bcommit\s+[0-9a-f]{5,}\b/i ||
3375		      ($line =~ /\bcommit\s*$/i && defined($rawlines[$linenr]) && $rawlines[$linenr] =~ /^\s*[0-9a-f]{5,}\b/i)) ||
3376		     ($line =~ /(?:\s|^)[0-9a-f]{12,40}(?:[\s"'\(\[]|$)/i &&
3377		      $line !~ /[\<\[][0-9a-f]{12,40}[\>\]]/i &&
3378		      $line !~ /\bfixes:\s*[0-9a-f]{12,40}/i))) {
3379			my $init_char = "c";
3380			my $orig_commit = "";
3381			my $short = 1;
3382			my $long = 0;
3383			my $case = 1;
3384			my $space = 1;
3385			my $id = '0123456789ab';
3386			my $orig_desc = "commit description";
3387			my $description = "";
3388			my $herectx = $herecurr;
3389			my $has_parens = 0;
3390			my $has_quotes = 0;
3391
3392			my $input = $line;
3393			if ($line =~ /(?:\bcommit\s+[0-9a-f]{5,}|\bcommit\s*$)/i) {
3394				for (my $n = 0; $n < 2; $n++) {
3395					if ($input =~ /\bcommit\s+[0-9a-f]{5,}\s*($balanced_parens)/i) {
3396						$orig_desc = $1;
3397						$has_parens = 1;
3398						# Always strip leading/trailing parens then double quotes if existing
3399						$orig_desc = substr($orig_desc, 1, -1);
3400						if ($orig_desc =~ /^".*"$/) {
3401							$orig_desc = substr($orig_desc, 1, -1);
3402							$has_quotes = 1;
3403						}
3404						last;
3405					}
3406					last if ($#lines < $linenr + $n);
3407					$input .= " " . trim($rawlines[$linenr + $n]);
3408					$herectx .= "$rawlines[$linenr + $n]\n";
3409				}
3410				$herectx = $herecurr if (!$has_parens);
3411			}
3412
3413			if ($input =~ /\b(c)ommit\s+([0-9a-f]{5,})\b/i) {
3414				$init_char = $1;
3415				$orig_commit = lc($2);
3416				$short = 0 if ($input =~ /\bcommit\s+[0-9a-f]{12,40}/i);
3417				$long = 1 if ($input =~ /\bcommit\s+[0-9a-f]{41,}/i);
3418				$space = 0 if ($input =~ /\bcommit [0-9a-f]/i);
3419				$case = 0 if ($input =~ /\b[Cc]ommit\s+[0-9a-f]{5,40}[^A-F]/);
3420			} elsif ($input =~ /\b([0-9a-f]{12,40})\b/i) {
3421				$orig_commit = lc($1);
3422			}
3423
3424			($id, $description) = git_commit_info($orig_commit,
3425							      $id, $orig_desc);
3426
3427			if (defined($id) &&
3428			    ($short || $long || $space || $case || ($orig_desc ne $description) || !$has_quotes) &&
3429			    $last_git_commit_id_linenr != $linenr - 1) {
3430				ERROR("GIT_COMMIT_ID",
3431				      "Please use git commit description style 'commit <12+ chars of sha1> (\"<title line>\")' - ie: '${init_char}ommit $id (\"$description\")'\n" . $herectx);
3432			}
3433			#don't report the next line if this line ends in commit and the sha1 hash is the next line
3434			$last_git_commit_id_linenr = $linenr if ($line =~ /\bcommit\s*$/i);
3435		}
3436
3437# Check for mailing list archives other than lore.kernel.org
3438		if ($rawline =~ m{http.*\b$obsolete_archives}) {
3439			WARN("PREFER_LORE_ARCHIVE",
3440			     "Use lore.kernel.org archive links when possible - see https://lore.kernel.org/lists.html\n" . $herecurr);
3441		}
3442
3443# Check for added, moved or deleted files
3444		if (!$reported_maintainer_file && !$in_commit_log &&
3445		    ($line =~ /^(?:new|deleted) file mode\s*\d+\s*$/ ||
3446		     $line =~ /^rename (?:from|to) [\w\/\.\-]+\s*$/ ||
3447		     ($line =~ /\{\s*([\w\/\.\-]*)\s*\=\>\s*([\w\/\.\-]*)\s*\}/ &&
3448		      (defined($1) || defined($2))))) {
3449			$is_patch = 1;
3450			$reported_maintainer_file = 1;
3451			WARN("FILE_PATH_CHANGES",
3452			     "added, moved or deleted file(s), does MAINTAINERS need updating?\n" . $herecurr);
3453		}
3454
3455# Check for adding new DT bindings not in schema format
3456		if (!$in_commit_log &&
3457		    ($line =~ /^new file mode\s*\d+\s*$/) &&
3458		    ($realfile =~ m@^Documentation/devicetree/bindings/.*\.txt$@)) {
3459			WARN("DT_SCHEMA_BINDING_PATCH",
3460			     "DT bindings should be in DT schema format. See: Documentation/devicetree/bindings/writing-schema.rst\n");
3461		}
3462
3463# Check for wrappage within a valid hunk of the file
3464		if ($realcnt != 0 && $line !~ m{^(?:\+|-| |\\ No newline|$)}) {
3465			ERROR("CORRUPTED_PATCH",
3466			      "patch seems to be corrupt (line wrapped?)\n" .
3467				$herecurr) if (!$emitted_corrupt++);
3468		}
3469
3470# UTF-8 regex found at http://www.w3.org/International/questions/qa-forms-utf-8.en.php
3471		if (($realfile =~ /^$/ || $line =~ /^\+/) &&
3472		    $rawline !~ m/^$UTF8*$/) {
3473			my ($utf8_prefix) = ($rawline =~ /^($UTF8*)/);
3474
3475			my $blank = copy_spacing($rawline);
3476			my $ptr = substr($blank, 0, length($utf8_prefix)) . "^";
3477			my $hereptr = "$hereline$ptr\n";
3478
3479			CHK("INVALID_UTF8",
3480			    "Invalid UTF-8, patch and commit message should be encoded in UTF-8\n" . $hereptr);
3481		}
3482
3483# Check if it's the start of a commit log
3484# (not a header line and we haven't seen the patch filename)
3485		if ($in_header_lines && $realfile =~ /^$/ &&
3486		    !($rawline =~ /^\s+(?:\S|$)/ ||
3487		      $rawline =~ /^(?:commit\b|from\b|[\w-]+:)/i)) {
3488			$in_header_lines = 0;
3489			$in_commit_log = 1;
3490			$has_commit_log = 1;
3491		}
3492
3493# Check if there is UTF-8 in a commit log when a mail header has explicitly
3494# declined it, i.e defined some charset where it is missing.
3495		if ($in_header_lines &&
3496		    $rawline =~ /^Content-Type:.+charset="(.+)".*$/ &&
3497		    $1 !~ /utf-8/i) {
3498			$non_utf8_charset = 1;
3499		}
3500
3501		if ($in_commit_log && $non_utf8_charset && $realfile =~ /^$/ &&
3502		    $rawline =~ /$NON_ASCII_UTF8/) {
3503			WARN("UTF8_BEFORE_PATCH",
3504			    "8-bit UTF-8 used in possible commit log\n" . $herecurr);
3505		}
3506
3507# Check for absolute kernel paths in commit message
3508		if ($tree && $in_commit_log) {
3509			while ($line =~ m{(?:^|\s)(/\S*)}g) {
3510				my $file = $1;
3511
3512				if ($file =~ m{^(.*?)(?::\d+)+:?$} &&
3513				    check_absolute_file($1, $herecurr)) {
3514					#
3515				} else {
3516					check_absolute_file($file, $herecurr);
3517				}
3518			}
3519		}
3520
3521# Check for various typo / spelling mistakes
3522		if (defined($misspellings) &&
3523		    ($in_commit_log || $line =~ /^(?:\+|Subject:)/i)) {
3524			my $rawline_utf8 = decode("utf8", $rawline);
3525			while ($rawline_utf8 =~ /(?:^|[^\w\-'`])($misspellings)(?:[^\w\-'`]|$)/gi) {
3526				my $typo = $1;
3527				my $blank = copy_spacing($rawline_utf8);
3528				my $ptr = substr($blank, 0, $-[1]) . "^" x length($typo);
3529				my $hereptr = "$hereline$ptr\n";
3530				my $typo_fix = $spelling_fix{lc($typo)};
3531				$typo_fix = ucfirst($typo_fix) if ($typo =~ /^[A-Z]/);
3532				$typo_fix = uc($typo_fix) if ($typo =~ /^[A-Z]+$/);
3533				my $msg_level = \&WARN;
3534				$msg_level = \&CHK if ($file);
3535				if (&{$msg_level}("TYPO_SPELLING",
3536						  "'$typo' may be misspelled - perhaps '$typo_fix'?\n" . $hereptr) &&
3537				    $fix) {
3538					$fixed[$fixlinenr] =~ s/(^|[^A-Za-z@])($typo)($|[^A-Za-z@])/$1$typo_fix$3/;
3539				}
3540			}
3541		}
3542
3543# check for invalid commit id
3544		if ($in_commit_log && $line =~ /(^fixes:|\bcommit)\s+([0-9a-f]{6,40})\b/i) {
3545			my $id;
3546			my $description;
3547			($id, $description) = git_commit_info($2, undef, undef);
3548			if (!defined($id)) {
3549				WARN("UNKNOWN_COMMIT_ID",
3550				     "Unknown commit id '$2', maybe rebased or not pulled?\n" . $herecurr);
3551			}
3552		}
3553
3554# check for repeated words separated by a single space
3555# avoid false positive from list command eg, '-rw-r--r-- 1 root root'
3556		if (($rawline =~ /^\+/ || $in_commit_log) &&
3557		    $rawline !~ /[bcCdDlMnpPs\?-][rwxsStT-]{9}/) {
3558			pos($rawline) = 1 if (!$in_commit_log);
3559			while ($rawline =~ /\b($word_pattern) (?=($word_pattern))/g) {
3560
3561				my $first = $1;
3562				my $second = $2;
3563				my $start_pos = $-[1];
3564				my $end_pos = $+[2];
3565				if ($first =~ /(?:struct|union|enum)/) {
3566					pos($rawline) += length($first) + length($second) + 1;
3567					next;
3568				}
3569
3570				next if (lc($first) ne lc($second));
3571				next if ($first eq 'long');
3572
3573				# check for character before and after the word matches
3574				my $start_char = '';
3575				my $end_char = '';
3576				$start_char = substr($rawline, $start_pos - 1, 1) if ($start_pos > ($in_commit_log ? 0 : 1));
3577				$end_char = substr($rawline, $end_pos, 1) if ($end_pos < length($rawline));
3578
3579				next if ($start_char =~ /^\S$/);
3580				next if (index(" \t.,;?!", $end_char) == -1);
3581
3582				# avoid repeating hex occurrences like 'ff ff fe 09 ...'
3583				if ($first =~ /\b[0-9a-f]{2,}\b/i) {
3584					next if (!exists($allow_repeated_words{lc($first)}));
3585				}
3586
3587				if (WARN("REPEATED_WORD",
3588					 "Possible repeated word: '$first'\n" . $herecurr) &&
3589				    $fix) {
3590					$fixed[$fixlinenr] =~ s/\b$first $second\b/$first/;
3591				}
3592			}
3593
3594			# if it's a repeated word on consecutive lines in a comment block
3595			if ($prevline =~ /$;+\s*$/ &&
3596			    $prevrawline =~ /($word_pattern)\s*$/) {
3597				my $last_word = $1;
3598				if ($rawline =~ /^\+\s*\*\s*$last_word /) {
3599					if (WARN("REPEATED_WORD",
3600						 "Possible repeated word: '$last_word'\n" . $hereprev) &&
3601					    $fix) {
3602						$fixed[$fixlinenr] =~ s/(\+\s*\*\s*)$last_word /$1/;
3603					}
3604				}
3605			}
3606		}
3607
3608# ignore non-hunk lines and lines being removed
3609		next if (!$hunk_line || $line =~ /^-/);
3610
3611#trailing whitespace
3612		if ($line =~ /^\+.*\015/) {
3613			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3614			if (ERROR("DOS_LINE_ENDINGS",
3615				  "DOS line endings\n" . $herevet) &&
3616			    $fix) {
3617				$fixed[$fixlinenr] =~ s/[\s\015]+$//;
3618			}
3619		} elsif ($rawline =~ /^\+.*\S\s+$/ || $rawline =~ /^\+\s+$/) {
3620			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3621			if (ERROR("TRAILING_WHITESPACE",
3622				  "trailing whitespace\n" . $herevet) &&
3623			    $fix) {
3624				$fixed[$fixlinenr] =~ s/\s+$//;
3625			}
3626
3627			$rpt_cleaners = 1;
3628		}
3629
3630# Check for FSF mailing addresses.
3631		if ($rawline =~ /\bwrite to the Free/i ||
3632		    $rawline =~ /\b675\s+Mass\s+Ave/i ||
3633		    $rawline =~ /\b59\s+Temple\s+Pl/i ||
3634		    $rawline =~ /\b51\s+Franklin\s+St/i) {
3635			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3636			my $msg_level = \&ERROR;
3637			$msg_level = \&CHK if ($file);
3638			&{$msg_level}("FSF_MAILING_ADDRESS",
3639				      "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)
3640		}
3641
3642# check for Kconfig help text having a real description
3643# Only applies when adding the entry originally, after that we do not have
3644# sufficient context to determine whether it is indeed long enough.
3645		if ($realfile =~ /Kconfig/ &&
3646		    # 'choice' is usually the last thing on the line (though
3647		    # Kconfig supports named choices), so use a word boundary
3648		    # (\b) rather than a whitespace character (\s)
3649		    $line =~ /^\+\s*(?:config|menuconfig|choice)\b/) {
3650			my $ln = $linenr;
3651			my $needs_help = 0;
3652			my $has_help = 0;
3653			my $help_length = 0;
3654			while (defined $lines[$ln]) {
3655				my $f = $lines[$ln++];
3656
3657				next if ($f =~ /^-/);
3658				last if ($f !~ /^[\+ ]/);	# !patch context
3659
3660				if ($f =~ /^\+\s*(?:bool|tristate|prompt)\s*["']/) {
3661					$needs_help = 1;
3662					next;
3663				}
3664				if ($f =~ /^\+\s*help\s*$/) {
3665					$has_help = 1;
3666					next;
3667				}
3668
3669				$f =~ s/^.//;	# strip patch context [+ ]
3670				$f =~ s/#.*//;	# strip # directives
3671				$f =~ s/^\s+//;	# strip leading blanks
3672				next if ($f =~ /^$/);	# skip blank lines
3673
3674				# At the end of this Kconfig block:
3675				# This only checks context lines in the patch
3676				# and so hopefully shouldn't trigger false
3677				# positives, even though some of these are
3678				# common words in help texts
3679				if ($f =~ /^(?:config|menuconfig|choice|endchoice|
3680					       if|endif|menu|endmenu|source)\b/x) {
3681					last;
3682				}
3683				$help_length++ if ($has_help);
3684			}
3685			if ($needs_help &&
3686			    $help_length < $min_conf_desc_length) {
3687				my $stat_real = get_stat_real($linenr, $ln - 1);
3688				WARN("CONFIG_DESCRIPTION",
3689				     "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");
3690			}
3691		}
3692
3693# check MAINTAINERS entries
3694		if ($realfile =~ /^MAINTAINERS$/) {
3695# check MAINTAINERS entries for the right form
3696			if ($rawline =~ /^\+[A-Z]:/ &&
3697			    $rawline !~ /^\+[A-Z]:\t\S/) {
3698				if (WARN("MAINTAINERS_STYLE",
3699					 "MAINTAINERS entries use one tab after TYPE:\n" . $herecurr) &&
3700				    $fix) {
3701					$fixed[$fixlinenr] =~ s/^(\+[A-Z]):\s*/$1:\t/;
3702				}
3703			}
3704# check MAINTAINERS entries for the right ordering too
3705			my $preferred_order = 'MRLSWQBCPTFXNK';
3706			if ($rawline =~ /^\+[A-Z]:/ &&
3707			    $prevrawline =~ /^[\+ ][A-Z]:/) {
3708				$rawline =~ /^\+([A-Z]):\s*(.*)/;
3709				my $cur = $1;
3710				my $curval = $2;
3711				$prevrawline =~ /^[\+ ]([A-Z]):\s*(.*)/;
3712				my $prev = $1;
3713				my $prevval = $2;
3714				my $curindex = index($preferred_order, $cur);
3715				my $previndex = index($preferred_order, $prev);
3716				if ($curindex < 0) {
3717					WARN("MAINTAINERS_STYLE",
3718					     "Unknown MAINTAINERS entry type: '$cur'\n" . $herecurr);
3719				} else {
3720					if ($previndex >= 0 && $curindex < $previndex) {
3721						WARN("MAINTAINERS_STYLE",
3722						     "Misordered MAINTAINERS entry - list '$cur:' before '$prev:'\n" . $hereprev);
3723					} elsif ((($prev eq 'F' && $cur eq 'F') ||
3724						  ($prev eq 'X' && $cur eq 'X')) &&
3725						 ($prevval cmp $curval) > 0) {
3726						WARN("MAINTAINERS_STYLE",
3727						     "Misordered MAINTAINERS entry - list file patterns in alphabetic order\n" . $hereprev);
3728					}
3729				}
3730			}
3731		}
3732
3733# check for DT compatible documentation
3734		if (defined $root &&
3735			(($realfile =~ /\.dtsi?$/ && $line =~ /^\+\s*compatible\s*=\s*\"/) ||
3736			 ($realfile =~ /\.[ch]$/ && $line =~ /^\+.*\.compatible\s*=\s*\"/))) {
3737
3738			my @compats = $rawline =~ /\"([a-zA-Z0-9\-\,\.\+_]+)\"/g;
3739
3740			my $dt_path = $root . "/Documentation/devicetree/bindings/";
3741			my $vp_file = $dt_path . "vendor-prefixes.yaml";
3742
3743			foreach my $compat (@compats) {
3744				my $compat2 = $compat;
3745				$compat2 =~ s/\,[a-zA-Z0-9]*\-/\,<\.\*>\-/;
3746				my $compat3 = $compat;
3747				$compat3 =~ s/\,([a-z]*)[0-9]*\-/\,$1<\.\*>\-/;
3748				`grep -Erq "$compat|$compat2|$compat3" $dt_path`;
3749				if ( $? >> 8 ) {
3750					WARN("UNDOCUMENTED_DT_STRING",
3751					     "DT compatible string \"$compat\" appears un-documented -- check $dt_path\n" . $herecurr);
3752				}
3753
3754				next if $compat !~ /^([a-zA-Z0-9\-]+)\,/;
3755				my $vendor = $1;
3756				`grep -Eq "\\"\\^\Q$vendor\E,\\.\\*\\":" $vp_file`;
3757				if ( $? >> 8 ) {
3758					WARN("UNDOCUMENTED_DT_STRING",
3759					     "DT compatible string vendor \"$vendor\" appears un-documented -- check $vp_file\n" . $herecurr);
3760				}
3761			}
3762		}
3763
3764# Check for RGMII phy-mode with delay on PCB
3765		if ($realfile =~ /\.(dts|dtsi|dtso)$/ &&
3766		    $line =~ /^\+\s*(phy-mode|phy-connection-type)\s*=\s*"/ &&
3767		    !ctx_has_comment($first_line, $linenr)) {
3768			my $prop = $1;
3769			my $mode = get_quoted_string($line, $rawline);
3770			if ($mode =~ /^"rgmii(?:|-rxid|-txid)"$/) {
3771				WARN("UNCOMMENTED_RGMII_MODE",
3772				     "$prop $mode without comment -- delays on the PCB should be described, otherwise use \"rgmii-id\"\n" . $herecurr);
3773			}
3774		}
3775
3776# check for using SPDX license tag at beginning of files
3777		if ($realline == $checklicenseline) {
3778			if ($rawline =~ /^[ \+]\s*\#\!\s*\//) {
3779				$checklicenseline = 2;
3780			} elsif ($rawline =~ /^\+/) {
3781				my $comment = "";
3782				if ($realfile =~ /\.(h|s|S)$/) {
3783					$comment = '/*';
3784				} elsif ($realfile =~ /\.(c|rs|dts|dtsi)$/) {
3785					$comment = '//';
3786				} elsif (($checklicenseline == 2) || $realfile =~ /\.(sh|pl|py|awk|tc|yaml)$/) {
3787					$comment = '#';
3788				} elsif ($realfile =~ /\.rst$/) {
3789					$comment = '..';
3790				}
3791
3792# check SPDX comment style for .[chsS] files
3793				if ($realfile =~ /\.[chsS]$/ &&
3794				    $rawline =~ /SPDX-License-Identifier:/ &&
3795				    $rawline !~ m@^\+\s*\Q$comment\E\s*@) {
3796					WARN("SPDX_LICENSE_TAG",
3797					     "Improper SPDX comment style for '$realfile', please use '$comment' instead\n" . $herecurr);
3798				}
3799
3800				if ($comment !~ /^$/ &&
3801				    $rawline !~ m@^\+\Q$comment\E SPDX-License-Identifier: @) {
3802					WARN("SPDX_LICENSE_TAG",
3803					     "Missing or malformed SPDX-License-Identifier tag in line $checklicenseline\n" . $herecurr);
3804				} elsif ($rawline =~ /(SPDX-License-Identifier: .*)/) {
3805					my $spdx_license = $1;
3806					if (!is_SPDX_License_valid($spdx_license)) {
3807						WARN("SPDX_LICENSE_TAG",
3808						     "'$spdx_license' is not supported in LICENSES/...\n" . $herecurr);
3809					}
3810					if ($realfile =~ m@^Documentation/devicetree/bindings/@ &&
3811					    $spdx_license !~ /GPL-2\.0(?:-only)? OR BSD-2-Clause/) {
3812						my $msg_level = \&WARN;
3813						$msg_level = \&CHK if ($file);
3814						if (&{$msg_level}("SPDX_LICENSE_TAG",
3815
3816								  "DT binding documents should be licensed (GPL-2.0-only OR BSD-2-Clause)\n" . $herecurr) &&
3817						    $fix) {
3818							$fixed[$fixlinenr] =~ s/SPDX-License-Identifier: .*/SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)/;
3819						}
3820					}
3821					if ($realfile =~ m@^include/dt-bindings/@ &&
3822					    $spdx_license !~ /GPL-2\.0(?:-only)? OR \S+/) {
3823						WARN("SPDX_LICENSE_TAG",
3824						     "DT binding headers should be licensed (GPL-2.0-only OR .*)\n" . $herecurr);
3825					}
3826				}
3827			}
3828		}
3829
3830# check for embedded filenames
3831		if ($rawline =~ /^\+.*\b\Q$realfile\E\b/) {
3832			WARN("EMBEDDED_FILENAME",
3833			     "It's generally not useful to have the filename in the file\n" . $herecurr);
3834		}
3835
3836# check we are in a valid source file if not then ignore this hunk
3837		next if ($realfile !~ /\.(h|c|rs|s|S|sh|dtsi|dts)$/);
3838
3839# check for using SPDX-License-Identifier on the wrong line number
3840		if ($realline != $checklicenseline &&
3841		    $rawline =~ /\bSPDX-License-Identifier:/ &&
3842		    substr($line, @-, @+ - @-) eq "$;" x (@+ - @-)) {
3843			WARN("SPDX_LICENSE_TAG",
3844			     "Misplaced SPDX-License-Identifier tag - use line $checklicenseline instead\n" . $herecurr);
3845		}
3846
3847# line length limit (with some exclusions)
3848#
3849# There are a few types of lines that may extend beyond $max_line_length:
3850#	logging functions like pr_info that end in a string
3851#	lines with a single string
3852#	#defines that are a single string
3853#	lines with an RFC3986 like URL
3854#
3855# There are 3 different line length message types:
3856# LONG_LINE_COMMENT	a comment starts before but extends beyond $max_line_length
3857# LONG_LINE_STRING	a string starts before but extends beyond $max_line_length
3858# LONG_LINE		all other lines longer than $max_line_length
3859#
3860# if LONG_LINE is ignored, the other 2 types are also ignored
3861#
3862
3863		if ($line =~ /^\+/ && $length > $max_line_length) {
3864			my $msg_type = "LONG_LINE";
3865
3866			# Check the allowed long line types first
3867
3868			# logging functions that end in a string that starts
3869			# before $max_line_length
3870			if ($line =~ /^\+\s*$logFunctions\s*\(\s*(?:(?:KERN_\S+\s*|[^"]*))?($String\s*(?:|,|\)\s*;)\s*)$/ &&
3871			    length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3872				$msg_type = "";
3873
3874			# lines with only strings (w/ possible termination)
3875			# #defines with only strings
3876			} elsif ($line =~ /^\+\s*$String\s*(?:\s*|,|\)\s*;)\s*$/ ||
3877				 $line =~ /^\+\s*#\s*define\s+\w+\s+$String$/) {
3878				$msg_type = "";
3879
3880			# More special cases
3881			} elsif ($line =~ /^\+.*\bEFI_GUID\s*\(/ ||
3882				 $line =~ /^\+\s*(?:\w+)?\s*DEFINE_PER_CPU/) {
3883				$msg_type = "";
3884
3885			# URL ($rawline is used in case the URL is in a comment)
3886			} elsif ($rawline =~ /^\+.*\b[a-z][\w\.\+\-]*:\/\/\S+/i) {
3887				$msg_type = "";
3888
3889			# Otherwise set the alternate message types
3890
3891			# a comment starts before $max_line_length
3892			} elsif ($line =~ /($;[\s$;]*)$/ &&
3893				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3894				$msg_type = "LONG_LINE_COMMENT"
3895
3896			# a quoted string starts before $max_line_length
3897			} elsif ($sline =~ /\s*($String(?:\s*(?:\\|,\s*|\)\s*;\s*))?)$/ &&
3898				 length(expand_tabs(substr($line, 1, length($line) - length($1) - 1))) <= $max_line_length) {
3899				$msg_type = "LONG_LINE_STRING"
3900			}
3901
3902			if ($msg_type ne "" &&
3903			    show_type("LONG_LINE") && show_type($msg_type)) {
3904				my $msg_level = \&WARN;
3905				$msg_level = \&CHK if ($file);
3906				&{$msg_level}($msg_type,
3907					      "line length of $length exceeds $max_line_length columns\n" . $herecurr);
3908			}
3909		}
3910
3911# check for adding lines without a newline.
3912		if ($line =~ /^\+/ && defined $lines[$linenr] && $lines[$linenr] =~ /^\\ No newline at end of file/) {
3913			if (WARN("MISSING_EOF_NEWLINE",
3914			         "adding a line without newline at end of file\n" . $herecurr) &&
3915			    $fix) {
3916				fix_delete_line($fixlinenr+1, "No newline at end of file");
3917			}
3918		}
3919
3920# check for .L prefix local symbols in .S files
3921		if ($realfile =~ /\.S$/ &&
3922		    $line =~ /^\+\s*(?:[A-Z]+_)?SYM_[A-Z]+_(?:START|END)(?:_[A-Z_]+)?\s*\(\s*\.L/) {
3923			WARN("AVOID_L_PREFIX",
3924			     "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);
3925		}
3926
3927# check we are in a valid source file C or perl if not then ignore this hunk
3928		next if ($realfile !~ /\.(h|c|pl|dtsi|dts)$/);
3929
3930# at the beginning of a line any tabs must come first and anything
3931# more than $tabsize must use tabs.
3932		if ($rawline =~ /^\+\s* \t\s*\S/ ||
3933		    $rawline =~ /^\+\s*        \s*/) {
3934			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3935			$rpt_cleaners = 1;
3936			if (ERROR("CODE_INDENT",
3937				  "code indent should use tabs where possible\n" . $herevet) &&
3938			    $fix) {
3939				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
3940			}
3941		}
3942
3943# check for space before tabs.
3944		if ($rawline =~ /^\+/ && $rawline =~ / \t/) {
3945			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
3946			if (WARN("SPACE_BEFORE_TAB",
3947				"please, no space before tabs\n" . $herevet) &&
3948			    $fix) {
3949				while ($fixed[$fixlinenr] =~
3950					   s/(^\+.*) {$tabsize,$tabsize}\t/$1\t\t/) {}
3951				while ($fixed[$fixlinenr] =~
3952					   s/(^\+.*) +\t/$1\t/) {}
3953			}
3954		}
3955
3956# check for assignments on the start of a line
3957		if ($sline =~ /^\+\s+($Assignment)[^=]/) {
3958			my $operator = $1;
3959			if (CHK("ASSIGNMENT_CONTINUATIONS",
3960				"Assignment operator '$1' should be on the previous line\n" . $hereprev) &&
3961			    $fix && $prevrawline =~ /^\+/) {
3962				# add assignment operator to the previous line, remove from current line
3963				$fixed[$fixlinenr - 1] .= " $operator";
3964				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3965			}
3966		}
3967
3968# check for && or || at the start of a line
3969		if ($rawline =~ /^\+\s*(&&|\|\|)/) {
3970			my $operator = $1;
3971			if (CHK("LOGICAL_CONTINUATIONS",
3972				"Logical continuations should be on the previous line\n" . $hereprev) &&
3973			    $fix && $prevrawline =~ /^\+/) {
3974				# insert logical operator at last non-comment, non-whitepsace char on previous line
3975				$prevline =~ /[\s$;]*$/;
3976				my $line_end = substr($prevrawline, $-[0]);
3977				$fixed[$fixlinenr - 1] =~ s/\Q$line_end\E$/ $operator$line_end/;
3978				$fixed[$fixlinenr] =~ s/\Q$operator\E\s*//;
3979			}
3980		}
3981
3982# check indentation starts on a tab stop
3983		if ($perl_version_ok &&
3984		    $sline =~ /^\+\t+( +)(?:$c90_Keywords\b|\{\s*$|\}\s*(?:else\b|while\b|\s*$)|$Declare\s*$Ident\s*[;=])/) {
3985			my $indent = length($1);
3986			if ($indent % $tabsize) {
3987				if (WARN("TABSTOP",
3988					 "Statements should start on a tabstop\n" . $herecurr) &&
3989				    $fix) {
3990					$fixed[$fixlinenr] =~ s@(^\+\t+) +@$1 . "\t" x ($indent/$tabsize)@e;
3991				}
3992			}
3993		}
3994
3995# check multi-line statement indentation matches previous line
3996		if ($perl_version_ok &&
3997		    $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|(?:\*\s*)*$Lval\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) {
3998			$prevline =~ /^\+(\t*)(.*)$/;
3999			my $oldindent = $1;
4000			my $rest = $2;
4001
4002			my $pos = pos_last_openparen($rest);
4003			if ($pos >= 0) {
4004				$line =~ /^(\+| )([ \t]*)/;
4005				my $newindent = $2;
4006
4007				my $goodtabindent = $oldindent .
4008					"\t" x ($pos / $tabsize) .
4009					" "  x ($pos % $tabsize);
4010				my $goodspaceindent = $oldindent . " "  x $pos;
4011
4012				if ($newindent ne $goodtabindent &&
4013				    $newindent ne $goodspaceindent) {
4014
4015					if (CHK("PARENTHESIS_ALIGNMENT",
4016						"Alignment should match open parenthesis\n" . $hereprev) &&
4017					    $fix && $line =~ /^\+/) {
4018						$fixed[$fixlinenr] =~
4019						    s/^\+[ \t]*/\+$goodtabindent/;
4020					}
4021				}
4022			}
4023		}
4024
4025# check for space after cast like "(int) foo" or "(struct foo) bar"
4026# avoid checking a few false positives:
4027#   "sizeof(<type>)" or "__alignof__(<type>)"
4028#   function pointer declarations like "(*foo)(int) = bar;"
4029#   structure definitions like "(struct foo) { 0 };"
4030#   multiline macros that define functions
4031#   known attributes or the __attribute__ keyword
4032		if ($line =~ /^\+(.*)\(\s*$Type\s*\)([ \t]++)((?![={]|\\$|$Attribute|__attribute__))/ &&
4033		    (!defined($1) || $1 !~ /\b(?:sizeof|__alignof__)\s*$/)) {
4034			if (CHK("SPACING",
4035				"No space is necessary after a cast\n" . $herecurr) &&
4036			    $fix) {
4037				$fixed[$fixlinenr] =~
4038				    s/(\(\s*$Type\s*\))[ \t]+/$1/;
4039			}
4040		}
4041
4042# Block comments use * on subsequent lines
4043		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4044		    $prevrawline =~ /^\+.*?\/\*/ &&		#starting /*
4045		    $prevrawline !~ /\*\/[ \t]*$/ &&		#no trailing */
4046		    $rawline =~ /^\+/ &&			#line is new
4047		    $rawline !~ /^\+[ \t]*\*/) {		#no leading *
4048			WARN("BLOCK_COMMENT_STYLE",
4049			     "Block comments use * on subsequent lines\n" . $hereprev);
4050		}
4051
4052# Block comments use */ on trailing lines
4053		if ($rawline !~ m@^\+[ \t]*\*/[ \t]*$@ &&	#trailing */
4054		    $rawline !~ m@^\+.*/\*.*\*/[ \t]*$@ &&	#inline /*...*/
4055		    $rawline !~ m@^\+.*\*{2,}/[ \t]*$@ &&	#trailing **/
4056		    $rawline =~ m@^\+[ \t]*.+\*\/[ \t]*$@) {	#non blank */
4057			WARN("BLOCK_COMMENT_STYLE",
4058			     "Block comments use a trailing */ on a separate line\n" . $herecurr);
4059		}
4060
4061# Block comment * alignment
4062		if ($prevline =~ /$;[ \t]*$/ &&			#ends in comment
4063		    $line =~ /^\+[ \t]*$;/ &&			#leading comment
4064		    $rawline =~ /^\+[ \t]*\*/ &&		#leading *
4065		    (($prevrawline =~ /^\+.*?\/\*/ &&		#leading /*
4066		      $prevrawline !~ /\*\/[ \t]*$/) ||		#no trailing */
4067		     $prevrawline =~ /^\+[ \t]*\*/)) {		#leading *
4068			my $oldindent;
4069			$prevrawline =~ m@^\+([ \t]*/?)\*@;
4070			if (defined($1)) {
4071				$oldindent = expand_tabs($1);
4072			} else {
4073				$prevrawline =~ m@^\+(.*/?)\*@;
4074				$oldindent = expand_tabs($1);
4075			}
4076			$rawline =~ m@^\+([ \t]*)\*@;
4077			my $newindent = $1;
4078			$newindent = expand_tabs($newindent);
4079			if (length($oldindent) ne length($newindent)) {
4080				WARN("BLOCK_COMMENT_STYLE",
4081				     "Block comments should align the * on each line\n" . $hereprev);
4082			}
4083		}
4084
4085# check for missing blank lines after struct/union declarations
4086# with exceptions for various attributes and macros
4087		if ($prevline =~ /^[\+ ]};?\s*$/ &&
4088		    $line =~ /^\+/ &&
4089		    !($line =~ /^\+\s*$/ ||
4090		      $line =~ /^\+\s*(?:EXPORT_SYMBOL|early_param|ALLOW_ERROR_INJECTION)/ ||
4091		      $line =~ /^\+\s*MODULE_/i ||
4092		      $line =~ /^\+\s*\#\s*(?:end|elif|else)/ ||
4093		      $line =~ /^\+[a-z_]*init/ ||
4094		      $line =~ /^\+\s*(?:static\s+)?[A-Z_]*ATTR/ ||
4095		      $line =~ /^\+\s*DECLARE/ ||
4096		      $line =~ /^\+\s*builtin_[\w_]*driver/ ||
4097		      $line =~ /^\+\s*__setup/)) {
4098			if (CHK("LINE_SPACING",
4099				"Please use a blank line after function/struct/union/enum declarations\n" . $hereprev) &&
4100			    $fix) {
4101				fix_insert_line($fixlinenr, "\+");
4102			}
4103		}
4104
4105# check for multiple consecutive blank lines
4106		if ($prevline =~ /^[\+ ]\s*$/ &&
4107		    $line =~ /^\+\s*$/ &&
4108		    $last_blank_line != ($linenr - 1)) {
4109			if (CHK("LINE_SPACING",
4110				"Please don't use multiple blank lines\n" . $hereprev) &&
4111			    $fix) {
4112				fix_delete_line($fixlinenr, $rawline);
4113			}
4114
4115			$last_blank_line = $linenr;
4116		}
4117
4118# check for missing blank lines after declarations
4119# (declarations must have the same indentation and not be at the start of line)
4120		if (($prevline =~ /\+(\s+)\S/) && $sline =~ /^\+$1\S/) {
4121			# use temporaries
4122			my $sl = $sline;
4123			my $pl = $prevline;
4124			# remove $Attribute/$Sparse uses to simplify comparisons
4125			$sl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4126			$pl =~ s/\b(?:$Attribute|$Sparse)\b//g;
4127			if (($pl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4128			# function pointer declarations
4129			     $pl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4130			# foo bar; where foo is some local typedef or #define
4131			     $pl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4132			# known declaration macros
4133			     $pl =~ /^\+\s+$declaration_macros/) &&
4134			# for "else if" which can look like "$Ident $Ident"
4135			    !($pl =~ /^\+\s+$c90_Keywords\b/ ||
4136			# other possible extensions of declaration lines
4137			      $pl =~ /(?:$Compare|$Assignment|$Operators)\s*$/ ||
4138			# not starting a section or a macro "\" extended line
4139			      $pl =~ /(?:\{\s*|\\)$/) &&
4140			# looks like a declaration
4141			    !($sl =~ /^\+\s+$Declare\s*$Ident\s*[=,;:\[]/ ||
4142			# function pointer declarations
4143			      $sl =~ /^\+\s+$Declare\s*\(\s*\*\s*$Ident\s*\)\s*[=,;:\[\(]/ ||
4144			# foo bar; where foo is some local typedef or #define
4145			      $sl =~ /^\+\s+$Ident(?:\s+|\s*\*\s*)$Ident\s*[=,;\[]/ ||
4146			# known declaration macros
4147			      $sl =~ /^\+\s+$declaration_macros/ ||
4148			# start of struct or union or enum
4149			      $sl =~ /^\+\s+(?:static\s+)?(?:const\s+)?(?:union|struct|enum|typedef)\b/ ||
4150			# start or end of block or continuation of declaration
4151			      $sl =~ /^\+\s+(?:$|[\{\}\.\#\"\?\:\(\[])/ ||
4152			# bitfield continuation
4153			      $sl =~ /^\+\s+$Ident\s*:\s*\d+\s*[,;]/ ||
4154			# other possible extensions of declaration lines
4155			      $sl =~ /^\+\s+\(?\s*(?:$Compare|$Assignment|$Operators)/)) {
4156				if (WARN("LINE_SPACING",
4157					 "Missing a blank line after declarations\n" . $hereprev) &&
4158				    $fix) {
4159					fix_insert_line($fixlinenr, "\+");
4160				}
4161			}
4162		}
4163
4164# check for spaces at the beginning of a line.
4165# Exceptions:
4166#  1) within comments
4167#  2) indented preprocessor commands
4168#  3) hanging labels
4169		if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/)  {
4170			my $herevet = "$here\n" . cat_vet($rawline) . "\n";
4171			if (WARN("LEADING_SPACE",
4172				 "please, no spaces at the start of a line\n" . $herevet) &&
4173			    $fix) {
4174				$fixed[$fixlinenr] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e;
4175			}
4176		}
4177
4178# check we are in a valid C source file if not then ignore this hunk
4179		next if ($realfile !~ /\.(h|c)$/);
4180
4181# check for unusual line ending [ or (
4182		if ($line =~ /^\+.*([\[\(])\s*$/) {
4183			CHK("OPEN_ENDED_LINE",
4184			    "Lines should not end with a '$1'\n" . $herecurr);
4185		}
4186
4187# check if this appears to be the start function declaration, save the name
4188		if ($sline =~ /^\+\{\s*$/ &&
4189		    $prevline =~ /^\+(?:(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*)?($Ident)\(/) {
4190			$context_function = $1;
4191		}
4192
4193# check if this appears to be the end of function declaration
4194		if ($sline =~ /^\+\}\s*$/) {
4195			undef $context_function;
4196		}
4197
4198# check indentation of any line with a bare else
4199# (but not if it is a multiple line "if (foo) return bar; else return baz;")
4200# if the previous line is a break or return and is indented 1 tab more...
4201		if ($sline =~ /^\+([\t]+)(?:}[ \t]*)?else(?:[ \t]*{)?\s*$/) {
4202			my $tabs = length($1) + 1;
4203			if ($prevline =~ /^\+\t{$tabs,$tabs}break\b/ ||
4204			    ($prevline =~ /^\+\t{$tabs,$tabs}return\b/ &&
4205			     defined $lines[$linenr] &&
4206			     $lines[$linenr] !~ /^[ \+]\t{$tabs,$tabs}return/)) {
4207				WARN("UNNECESSARY_ELSE",
4208				     "else is not generally useful after a break or return\n" . $hereprev);
4209			}
4210		}
4211
4212# check indentation of a line with a break;
4213# if the previous line is a goto, return or break
4214# and is indented the same # of tabs
4215		if ($sline =~ /^\+([\t]+)break\s*;\s*$/) {
4216			my $tabs = $1;
4217			if ($prevline =~ /^\+$tabs(goto|return|break)\b/) {
4218				if (WARN("UNNECESSARY_BREAK",
4219					 "break is not useful after a $1\n" . $hereprev) &&
4220				    $fix) {
4221					fix_delete_line($fixlinenr, $rawline);
4222				}
4223			}
4224		}
4225
4226# check for RCS/CVS revision markers
4227		if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) {
4228			WARN("CVS_KEYWORD",
4229			     "CVS style keyword markers, these will _not_ be updated\n". $herecurr);
4230		}
4231
4232# check for old HOTPLUG __dev<foo> section markings
4233		if ($line =~ /\b(__dev(init|exit)(data|const|))\b/) {
4234			WARN("HOTPLUG_SECTION",
4235			     "Using $1 is unnecessary\n" . $herecurr);
4236		}
4237
4238# Check for potential 'bare' types
4239		my ($stat, $cond, $line_nr_next, $remain_next, $off_next,
4240		    $realline_next);
4241#print "LINE<$line>\n";
4242		if ($linenr > $suppress_statement &&
4243		    $realcnt && $sline =~ /.\s*\S/) {
4244			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4245				ctx_statement_block($linenr, $realcnt, 0);
4246			$stat =~ s/\n./\n /g;
4247			$cond =~ s/\n./\n /g;
4248
4249#print "linenr<$linenr> <$stat>\n";
4250			# If this statement has no statement boundaries within
4251			# it there is no point in retrying a statement scan
4252			# until we hit end of it.
4253			my $frag = $stat; $frag =~ s/;+\s*$//;
4254			if ($frag !~ /(?:{|;)/) {
4255#print "skip<$line_nr_next>\n";
4256				$suppress_statement = $line_nr_next;
4257			}
4258
4259			# Find the real next line.
4260			$realline_next = $line_nr_next;
4261			if (defined $realline_next &&
4262			    (!defined $lines[$realline_next - 1] ||
4263			     substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) {
4264				$realline_next++;
4265			}
4266
4267			my $s = $stat;
4268			$s =~ s/{.*$//s;
4269
4270			# Ignore goto labels.
4271			if ($s =~ /$Ident:\*$/s) {
4272
4273			# Ignore functions being called
4274			} elsif ($s =~ /^.\s*$Ident\s*\(/s) {
4275
4276			} elsif ($s =~ /^.\s*else\b/s) {
4277
4278			# declarations always start with types
4279			} 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) {
4280				my $type = $1;
4281				$type =~ s/\s+/ /g;
4282				possible($type, "A:" . $s);
4283
4284			# definitions in global scope can only start with types
4285			} elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) {
4286				possible($1, "B:" . $s);
4287			}
4288
4289			# any (foo ... *) is a pointer cast, and foo is a type
4290			while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) {
4291				possible($1, "C:" . $s);
4292			}
4293
4294			# Check for any sort of function declaration.
4295			# int foo(something bar, other baz);
4296			# void (*store_gdt)(x86_descr_ptr *);
4297			if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) {
4298				my ($name_len) = length($1);
4299
4300				my $ctx = $s;
4301				substr($ctx, 0, $name_len + 1, '');
4302				$ctx =~ s/\)[^\)]*$//;
4303
4304				for my $arg (split(/\s*,\s*/, $ctx)) {
4305					if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) {
4306
4307						possible($1, "D:" . $s);
4308					}
4309				}
4310			}
4311
4312		}
4313
4314#
4315# Checks which may be anchored in the context.
4316#
4317
4318# Check for switch () and associated case and default
4319# statements should be at the same indent.
4320		if ($line=~/\bswitch\s*\(.*\)/) {
4321			my $err = '';
4322			my $sep = '';
4323			my @ctx = ctx_block_outer($linenr, $realcnt);
4324			shift(@ctx);
4325			for my $ctx (@ctx) {
4326				my ($clen, $cindent) = line_stats($ctx);
4327				if ($ctx =~ /^\+\s*(case\s+|default:)/ &&
4328							$indent != $cindent) {
4329					$err .= "$sep$ctx\n";
4330					$sep = '';
4331				} else {
4332					$sep = "[...]\n";
4333				}
4334			}
4335			if ($err ne '') {
4336				ERROR("SWITCH_CASE_INDENT_LEVEL",
4337				      "switch and case should be at the same indent\n$hereline$err");
4338			}
4339		}
4340
4341# if/while/etc brace do not go on next line, unless defining a do while loop,
4342# or if that brace on the next line is for something else
4343		if ($line =~ /(.*)\b((?:if|while|for|switch|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) {
4344			my $pre_ctx = "$1$2";
4345
4346			my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0);
4347
4348			if ($line =~ /^\+\t{6,}/) {
4349				WARN("DEEP_INDENTATION",
4350				     "Too many leading tabs - consider code refactoring\n" . $herecurr);
4351			}
4352
4353			my $ctx_cnt = $realcnt - $#ctx - 1;
4354			my $ctx = join("\n", @ctx);
4355
4356			my $ctx_ln = $linenr;
4357			my $ctx_skip = $realcnt;
4358
4359			while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt &&
4360					defined $lines[$ctx_ln - 1] &&
4361					$lines[$ctx_ln - 1] =~ /^-/)) {
4362				##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n";
4363				$ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/);
4364				$ctx_ln++;
4365			}
4366
4367			#print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n";
4368			#print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n";
4369
4370			if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln - 1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) {
4371				ERROR("OPEN_BRACE",
4372				      "that open brace { should be on the previous line\n" .
4373					"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4374			}
4375			if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ &&
4376			    $ctx =~ /\)\s*\;\s*$/ &&
4377			    defined $lines[$ctx_ln - 1])
4378			{
4379				my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]);
4380				if ($nindent > $indent) {
4381					WARN("TRAILING_SEMICOLON",
4382					     "trailing semicolon indicates no statements, indent implies otherwise\n" .
4383						"$here\n$ctx\n$rawlines[$ctx_ln - 1]\n");
4384				}
4385			}
4386		}
4387
4388# Check relative indent for conditionals and blocks.
4389		if ($line =~ /\b(?:(?:if|while|for|(?:[a-z_]+|)for_each[a-z_]+)\s*\(|(?:do|else)\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) {
4390			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
4391				ctx_statement_block($linenr, $realcnt, 0)
4392					if (!defined $stat);
4393			my ($s, $c) = ($stat, $cond);
4394
4395			substr($s, 0, length($c), '');
4396
4397			# remove inline comments
4398			$s =~ s/$;/ /g;
4399			$c =~ s/$;/ /g;
4400
4401			# Find out how long the conditional actually is.
4402			my @newlines = ($c =~ /\n/gs);
4403			my $cond_lines = 1 + $#newlines;
4404
4405			# Make sure we remove the line prefixes as we have
4406			# none on the first line, and are going to readd them
4407			# where necessary.
4408			$s =~ s/\n./\n/gs;
4409			while ($s =~ /\n\s+\\\n/) {
4410				$cond_lines += $s =~ s/\n\s+\\\n/\n/g;
4411			}
4412
4413			# We want to check the first line inside the block
4414			# starting at the end of the conditional, so remove:
4415			#  1) any blank line termination
4416			#  2) any opening brace { on end of the line
4417			#  3) any do (...) {
4418			my $continuation = 0;
4419			my $check = 0;
4420			$s =~ s/^.*\bdo\b//;
4421			$s =~ s/^\s*{//;
4422			if ($s =~ s/^\s*\\//) {
4423				$continuation = 1;
4424			}
4425			if ($s =~ s/^\s*?\n//) {
4426				$check = 1;
4427				$cond_lines++;
4428			}
4429
4430			# Also ignore a loop construct at the end of a
4431			# preprocessor statement.
4432			if (($prevline =~ /^.\s*#\s*define\s/ ||
4433			    $prevline =~ /\\\s*$/) && $continuation == 0) {
4434				$check = 0;
4435			}
4436
4437			my $cond_ptr = -1;
4438			$continuation = 0;
4439			while ($cond_ptr != $cond_lines) {
4440				$cond_ptr = $cond_lines;
4441
4442				# If we see an #else/#elif then the code
4443				# is not linear.
4444				if ($s =~ /^\s*\#\s*(?:else|elif)/) {
4445					$check = 0;
4446				}
4447
4448				# Ignore:
4449				#  1) blank lines, they should be at 0,
4450				#  2) preprocessor lines, and
4451				#  3) labels.
4452				if ($continuation ||
4453				    $s =~ /^\s*?\n/ ||
4454				    $s =~ /^\s*#\s*?/ ||
4455				    $s =~ /^\s*$Ident\s*:/) {
4456					$continuation = ($s =~ /^.*?\\\n/) ? 1 : 0;
4457					if ($s =~ s/^.*?\n//) {
4458						$cond_lines++;
4459					}
4460				}
4461			}
4462
4463			my (undef, $sindent) = line_stats("+" . $s);
4464			my $stat_real = raw_line($linenr, $cond_lines);
4465
4466			# Check if either of these lines are modified, else
4467			# this is not this patch's fault.
4468			if (!defined($stat_real) ||
4469			    $stat !~ /^\+/ && $stat_real !~ /^\+/) {
4470				$check = 0;
4471			}
4472			if (defined($stat_real) && $cond_lines > 1) {
4473				$stat_real = "[...]\n$stat_real";
4474			}
4475
4476			#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";
4477
4478			if ($check && $s ne '' &&
4479			    (($sindent % $tabsize) != 0 ||
4480			     ($sindent < $indent) ||
4481			     ($sindent == $indent &&
4482			      ($s !~ /^\s*(?:\}|\{|else\b)/)) ||
4483			     ($sindent > $indent + $tabsize))) {
4484				WARN("SUSPECT_CODE_INDENT",
4485				     "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n");
4486			}
4487		}
4488
4489		# Track the 'values' across context and added lines.
4490		my $opline = $line; $opline =~ s/^./ /;
4491		my ($curr_values, $curr_vars) =
4492				annotate_values($opline . "\n", $prev_values);
4493		$curr_values = $prev_values . $curr_values;
4494		if ($dbg_values) {
4495			my $outline = $opline; $outline =~ s/\t/ /g;
4496			print "$linenr > .$outline\n";
4497			print "$linenr > $curr_values\n";
4498			print "$linenr >  $curr_vars\n";
4499		}
4500		$prev_values = substr($curr_values, -1);
4501
4502#ignore lines not being added
4503		next if ($line =~ /^[^\+]/);
4504
4505# check for self assignments used to avoid compiler warnings
4506# e.g.:	int foo = foo, *bar = NULL;
4507#	struct foo bar = *(&(bar));
4508		if ($line =~ /^\+\s*(?:$Declare)?([A-Za-z_][A-Za-z\d_]*)\s*=/) {
4509			my $var = $1;
4510			if ($line =~ /^\+\s*(?:$Declare)?$var\s*=\s*(?:$var|\*\s*\(?\s*&\s*\(?\s*$var\s*\)?\s*\)?)\s*[;,]/) {
4511				WARN("SELF_ASSIGNMENT",
4512				     "Do not use self-assignments to avoid compiler warnings\n" . $herecurr);
4513			}
4514		}
4515
4516# check for dereferences that span multiple lines
4517		if ($prevline =~ /^\+.*$Lval\s*(?:\.|->)\s*$/ &&
4518		    $line =~ /^\+\s*(?!\#\s*(?!define\s+|if))\s*$Lval/) {
4519			$prevline =~ /($Lval\s*(?:\.|->))\s*$/;
4520			my $ref = $1;
4521			$line =~ /^.\s*($Lval)/;
4522			$ref .= $1;
4523			$ref =~ s/\s//g;
4524			WARN("MULTILINE_DEREFERENCE",
4525			     "Avoid multiple line dereference - prefer '$ref'\n" . $hereprev);
4526		}
4527
4528# check for declarations of signed or unsigned without int
4529		while ($line =~ m{\b($Declare)\s*(?!char\b|short\b|int\b|long\b)\s*($Ident)?\s*[=,;\[\)\(]}g) {
4530			my $type = $1;
4531			my $var = $2;
4532			$var = "" if (!defined $var);
4533			if ($type =~ /^(?:(?:$Storage|$Inline|$Attribute)\s+)*((?:un)?signed)((?:\s*\*)*)\s*$/) {
4534				my $sign = $1;
4535				my $pointer = $2;
4536
4537				$pointer = "" if (!defined $pointer);
4538
4539				if (WARN("UNSPECIFIED_INT",
4540					 "Prefer '" . trim($sign) . " int" . rtrim($pointer) . "' to bare use of '$sign" . rtrim($pointer) . "'\n" . $herecurr) &&
4541				    $fix) {
4542					my $decl = trim($sign) . " int ";
4543					my $comp_pointer = $pointer;
4544					$comp_pointer =~ s/\s//g;
4545					$decl .= $comp_pointer;
4546					$decl = rtrim($decl) if ($var eq "");
4547					$fixed[$fixlinenr] =~ s@\b$sign\s*\Q$pointer\E\s*$var\b@$decl$var@;
4548				}
4549			}
4550		}
4551
4552# TEST: allow direct testing of the type matcher.
4553		if ($dbg_type) {
4554			if ($line =~ /^.\s*$Declare\s*$/) {
4555				ERROR("TEST_TYPE",
4556				      "TEST: is type\n" . $herecurr);
4557			} elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) {
4558				ERROR("TEST_NOT_TYPE",
4559				      "TEST: is not type ($1 is)\n". $herecurr);
4560			}
4561			next;
4562		}
4563# TEST: allow direct testing of the attribute matcher.
4564		if ($dbg_attr) {
4565			if ($line =~ /^.\s*$Modifier\s*$/) {
4566				ERROR("TEST_ATTR",
4567				      "TEST: is attr\n" . $herecurr);
4568			} elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) {
4569				ERROR("TEST_NOT_ATTR",
4570				      "TEST: is not attr ($1 is)\n". $herecurr);
4571			}
4572			next;
4573		}
4574
4575# check for initialisation to aggregates open brace on the next line
4576		if ($line =~ /^.\s*{/ &&
4577		    $prevline =~ /(?:^|[^=])=\s*$/) {
4578			if (ERROR("OPEN_BRACE",
4579				  "that open brace { should be on the previous line\n" . $hereprev) &&
4580			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4581				fix_delete_line($fixlinenr - 1, $prevrawline);
4582				fix_delete_line($fixlinenr, $rawline);
4583				my $fixedline = $prevrawline;
4584				$fixedline =~ s/\s*=\s*$/ = {/;
4585				fix_insert_line($fixlinenr, $fixedline);
4586				$fixedline = $line;
4587				$fixedline =~ s/^(.\s*)\{\s*/$1/;
4588				fix_insert_line($fixlinenr, $fixedline);
4589			}
4590		}
4591
4592#
4593# Checks which are anchored on the added line.
4594#
4595
4596# check for malformed paths in #include statements (uses RAW line)
4597		if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) {
4598			my $path = $1;
4599			if ($path =~ m{//}) {
4600				ERROR("MALFORMED_INCLUDE",
4601				      "malformed #include filename\n" . $herecurr);
4602			}
4603			if ($path =~ "^uapi/" && $realfile =~ m@\binclude/uapi/@) {
4604				ERROR("UAPI_INCLUDE",
4605				      "No #include in ...include/uapi/... should use a uapi/ path prefix\n" . $herecurr);
4606			}
4607		}
4608
4609# no C99 // comments
4610		if ($line =~ m{//}) {
4611			if (ERROR("C99_COMMENTS",
4612				  "do not use C99 // comments\n" . $herecurr) &&
4613			    $fix) {
4614				my $line = $fixed[$fixlinenr];
4615				if ($line =~ /\/\/(.*)$/) {
4616					my $comment = trim($1);
4617					$fixed[$fixlinenr] =~ s@\/\/(.*)$@/\* $comment \*/@;
4618				}
4619			}
4620		}
4621		# Remove C99 comments.
4622		$line =~ s@//.*@@;
4623		$opline =~ s@//.*@@;
4624
4625# EXPORT_SYMBOL should immediately follow the thing it is exporting, consider
4626# the whole statement.
4627#print "APW <$lines[$realline_next - 1]>\n";
4628		if (defined $realline_next &&
4629		    exists $lines[$realline_next - 1] &&
4630		    !defined $suppress_export{$realline_next} &&
4631		    ($lines[$realline_next - 1] =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4632			# Handle definitions which produce identifiers with
4633			# a prefix:
4634			#   XXX(foo);
4635			#   EXPORT_SYMBOL(something_foo);
4636			my $name = $1;
4637			$name =~ s/^\s*($Ident).*/$1/;
4638			if ($stat =~ /^(?:.\s*}\s*\n)?.([A-Z_]+)\s*\(\s*($Ident)/ &&
4639			    $name =~ /^${Ident}_$2/) {
4640#print "FOO C name<$name>\n";
4641				$suppress_export{$realline_next} = 1;
4642
4643			} elsif ($stat !~ /(?:
4644				\n.}\s*$|
4645				^.DEFINE_$Ident\(\Q$name\E\)|
4646				^.DECLARE_$Ident\(\Q$name\E\)|
4647				^.LIST_HEAD\(\Q$name\E\)|
4648				^.(?:$Storage\s+)?$Type\s*\(\s*\*\s*\Q$name\E\s*\)\s*\(|
4649				\b\Q$name\E(?:\s+$Attribute)*\s*(?:;|=|\[|\()
4650			    )/x) {
4651#print "FOO A<$lines[$realline_next - 1]> stat<$stat> name<$name>\n";
4652				$suppress_export{$realline_next} = 2;
4653			} else {
4654				$suppress_export{$realline_next} = 1;
4655			}
4656		}
4657		if (!defined $suppress_export{$linenr} &&
4658		    $prevline =~ /^.\s*$/ &&
4659		    ($line =~ /EXPORT_SYMBOL.*\((.*)\)/)) {
4660#print "FOO B <$lines[$linenr - 1]>\n";
4661			$suppress_export{$linenr} = 2;
4662		}
4663		if (defined $suppress_export{$linenr} &&
4664		    $suppress_export{$linenr} == 2) {
4665			WARN("EXPORT_SYMBOL",
4666			     "EXPORT_SYMBOL(foo); should immediately follow its function/variable\n" . $herecurr);
4667		}
4668
4669# check for global initialisers.
4670		if ($line =~ /^\+$Type\s*$Ident(?:\s+$Modifier)*\s*=\s*($zero_initializer)\s*;/ &&
4671		    !exclude_global_initialisers($realfile)) {
4672			if (ERROR("GLOBAL_INITIALISERS",
4673				  "do not initialise globals to $1\n" . $herecurr) &&
4674			    $fix) {
4675				$fixed[$fixlinenr] =~ s/(^.$Type\s*$Ident(?:\s+$Modifier)*)\s*=\s*$zero_initializer\s*;/$1;/;
4676			}
4677		}
4678# check for static initialisers.
4679		if ($line =~ /^\+.*\bstatic\s.*=\s*($zero_initializer)\s*;/) {
4680			if (ERROR("INITIALISED_STATIC",
4681				  "do not initialise statics to $1\n" .
4682				      $herecurr) &&
4683			    $fix) {
4684				$fixed[$fixlinenr] =~ s/(\bstatic\s.*?)\s*=\s*$zero_initializer\s*;/$1;/;
4685			}
4686		}
4687
4688# check for misordered declarations of char/short/int/long with signed/unsigned
4689		while ($sline =~ m{(\b$TypeMisordered\b)}g) {
4690			my $tmp = trim($1);
4691			WARN("MISORDERED_TYPE",
4692			     "type '$tmp' should be specified in [[un]signed] [short|int|long|long long] order\n" . $herecurr);
4693		}
4694
4695# check for unnecessary <signed> int declarations of short/long/long long
4696		while ($sline =~ m{\b($TypeMisordered(\s*\*)*|$C90_int_types)\b}g) {
4697			my $type = trim($1);
4698			next if ($type !~ /\bint\b/);
4699			next if ($type !~ /\b(?:short|long\s+long|long)\b/);
4700			my $new_type = $type;
4701			$new_type =~ s/\b\s*int\s*\b/ /;
4702			$new_type =~ s/\b\s*(?:un)?signed\b\s*/ /;
4703			$new_type =~ s/^const\s+//;
4704			$new_type = "unsigned $new_type" if ($type =~ /\bunsigned\b/);
4705			$new_type = "const $new_type" if ($type =~ /^const\b/);
4706			$new_type =~ s/\s+/ /g;
4707			$new_type = trim($new_type);
4708			if (WARN("UNNECESSARY_INT",
4709				 "Prefer '$new_type' over '$type' as the int is unnecessary\n" . $herecurr) &&
4710			    $fix) {
4711				$fixed[$fixlinenr] =~ s/\b\Q$type\E\b/$new_type/;
4712			}
4713		}
4714
4715# check for static const char * arrays.
4716		if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) {
4717			WARN("STATIC_CONST_CHAR_ARRAY",
4718			     "static const char * array should probably be static const char * const\n" .
4719				$herecurr);
4720		}
4721
4722# check for initialized const char arrays that should be static const
4723		if ($line =~ /^\+\s*const\s+(char|unsigned\s+char|_*u8|(?:[us]_)?int8_t)\s+\w+\s*\[\s*(?:\w+\s*)?\]\s*=\s*"/) {
4724			if (WARN("STATIC_CONST_CHAR_ARRAY",
4725				 "const array should probably be static const\n" . $herecurr) &&
4726			    $fix) {
4727				$fixed[$fixlinenr] =~ s/(^.\s*)const\b/${1}static const/;
4728			}
4729		}
4730
4731# check for static char foo[] = "bar" declarations.
4732		if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) {
4733			WARN("STATIC_CONST_CHAR_ARRAY",
4734			     "static char array declaration should probably be static const char\n" .
4735				$herecurr);
4736		}
4737
4738# check for const <foo> const where <foo> is not a pointer or array type
4739		if ($sline =~ /\bconst\s+($BasicType)\s+const\b/) {
4740			my $found = $1;
4741			if ($sline =~ /\bconst\s+\Q$found\E\s+const\b\s*\*/) {
4742				WARN("CONST_CONST",
4743				     "'const $found const *' should probably be 'const $found * const'\n" . $herecurr);
4744			} elsif ($sline !~ /\bconst\s+\Q$found\E\s+const\s+\w+\s*\[/) {
4745				WARN("CONST_CONST",
4746				     "'const $found const' should probably be 'const $found'\n" . $herecurr);
4747			}
4748		}
4749
4750# check for const static or static <non ptr type> const declarations
4751# prefer 'static const <foo>' over 'const static <foo>' and 'static <foo> const'
4752		if ($sline =~ /^\+\s*const\s+static\s+($Type)\b/ ||
4753		    $sline =~ /^\+\s*static\s+($BasicType)\s+const\b/) {
4754			if (WARN("STATIC_CONST",
4755				 "Move const after static - use 'static const $1'\n" . $herecurr) &&
4756			    $fix) {
4757				$fixed[$fixlinenr] =~ s/\bconst\s+static\b/static const/;
4758				$fixed[$fixlinenr] =~ s/\bstatic\s+($BasicType)\s+const\b/static const $1/;
4759			}
4760		}
4761
4762# check for non-global char *foo[] = {"bar", ...} declarations.
4763		if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) {
4764			WARN("STATIC_CONST_CHAR_ARRAY",
4765			     "char * array declaration might be better as static const\n" .
4766				$herecurr);
4767		}
4768
4769# check for sizeof(foo)/sizeof(foo[0]) that could be ARRAY_SIZE(foo)
4770		if ($line =~ m@\bsizeof\s*\(\s*($Lval)\s*\)@) {
4771			my $array = $1;
4772			if ($line =~ m@\b(sizeof\s*\(\s*\Q$array\E\s*\)\s*/\s*sizeof\s*\(\s*\Q$array\E\s*\[\s*0\s*\]\s*\))@) {
4773				my $array_div = $1;
4774				if (WARN("ARRAY_SIZE",
4775					 "Prefer ARRAY_SIZE($array)\n" . $herecurr) &&
4776				    $fix) {
4777					$fixed[$fixlinenr] =~ s/\Q$array_div\E/ARRAY_SIZE($array)/;
4778				}
4779			}
4780		}
4781
4782# check for function declarations without arguments like "int foo()"
4783		if ($line =~ /(\b$Type\s*$Ident)\s*\(\s*\)/) {
4784			if (ERROR("FUNCTION_WITHOUT_ARGS",
4785				  "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) &&
4786			    $fix) {
4787				$fixed[$fixlinenr] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/;
4788			}
4789		}
4790
4791# check for new typedefs, only function parameters and sparse annotations
4792# make sense.
4793		if ($line =~ /\btypedef\s/ &&
4794		    $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ &&
4795		    $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ &&
4796		    $line !~ /\b$typeTypedefs\b/ &&
4797		    $line !~ /\b__bitwise\b/) {
4798			WARN("NEW_TYPEDEFS",
4799			     "do not add new typedefs\n" . $herecurr);
4800		}
4801
4802# * goes on variable not on type
4803		# (char*[ const])
4804		while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) {
4805			#print "AA<$1>\n";
4806			my ($ident, $from, $to) = ($1, $2, $2);
4807
4808			# Should start with a space.
4809			$to =~ s/^(\S)/ $1/;
4810			# Should not end with a space.
4811			$to =~ s/\s+$//;
4812			# '*'s should not have spaces between.
4813			while ($to =~ s/\*\s+\*/\*\*/) {
4814			}
4815
4816##			print "1: from<$from> to<$to> ident<$ident>\n";
4817			if ($from ne $to) {
4818				if (ERROR("POINTER_LOCATION",
4819					  "\"(foo$from)\" should be \"(foo$to)\"\n" .  $herecurr) &&
4820				    $fix) {
4821					my $sub_from = $ident;
4822					my $sub_to = $ident;
4823					$sub_to =~ s/\Q$from\E/$to/;
4824					$fixed[$fixlinenr] =~
4825					    s@\Q$sub_from\E@$sub_to@;
4826				}
4827			}
4828		}
4829		while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) {
4830			#print "BB<$1>\n";
4831			my ($match, $from, $to, $ident) = ($1, $2, $2, $3);
4832
4833			# Should start with a space.
4834			$to =~ s/^(\S)/ $1/;
4835			# Should not end with a space.
4836			$to =~ s/\s+$//;
4837			# '*'s should not have spaces between.
4838			while ($to =~ s/\*\s+\*/\*\*/) {
4839			}
4840			# Modifiers should have spaces.
4841			$to =~ s/(\b$Modifier$)/$1 /;
4842
4843##			print "2: from<$from> to<$to> ident<$ident>\n";
4844			if ($from ne $to && $ident !~ /^$Modifier$/) {
4845				if (ERROR("POINTER_LOCATION",
4846					  "\"foo${from}bar\" should be \"foo${to}bar\"\n" .  $herecurr) &&
4847				    $fix) {
4848
4849					my $sub_from = $match;
4850					my $sub_to = $match;
4851					$sub_to =~ s/\Q$from\E/$to/;
4852					$fixed[$fixlinenr] =~
4853					    s@\Q$sub_from\E@$sub_to@;
4854				}
4855			}
4856		}
4857
4858# do not use BUG() or variants
4859		if ($line =~ /\b(?!AA_|BUILD_|IDA_|KVM_|RWLOCK_|snd_|SPIN_)(?:[a-zA-Z_]*_)?BUG(?:_ON)?(?:_[A-Z_]+)?\s*\(/) {
4860			my $msg_level = \&WARN;
4861			$msg_level = \&CHK if ($file);
4862			&{$msg_level}("AVOID_BUG",
4863				      "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);
4864		}
4865
4866# avoid LINUX_VERSION_CODE
4867		if ($line =~ /\bLINUX_VERSION_CODE\b/) {
4868			WARN("LINUX_VERSION_CODE",
4869			     "LINUX_VERSION_CODE should be avoided, code should be for the version to which it is merged\n" . $herecurr);
4870		}
4871
4872# check for uses of printk_ratelimit
4873		if ($line =~ /\bprintk_ratelimit\s*\(/) {
4874			WARN("PRINTK_RATELIMITED",
4875			     "Prefer printk_ratelimited or pr_<level>_ratelimited to printk_ratelimit\n" . $herecurr);
4876		}
4877
4878# printk should use KERN_* levels
4879		if ($line =~ /\bprintk\s*\(\s*(?!KERN_[A-Z]+\b)/) {
4880			WARN("PRINTK_WITHOUT_KERN_LEVEL",
4881			     "printk() should include KERN_<LEVEL> facility level\n" . $herecurr);
4882		}
4883
4884# prefer variants of (subsystem|netdev|dev|pr)_<level> to printk(KERN_<LEVEL>
4885		if ($line =~ /\b(printk(_once|_ratelimited)?)\s*\(\s*KERN_([A-Z]+)/) {
4886			my $printk = $1;
4887			my $modifier = $2;
4888			my $orig = $3;
4889			$modifier = "" if (!defined($modifier));
4890			my $level = lc($orig);
4891			$level = "warn" if ($level eq "warning");
4892			my $level2 = $level;
4893			$level2 = "dbg" if ($level eq "debug");
4894			$level .= $modifier;
4895			$level2 .= $modifier;
4896			WARN("PREFER_PR_LEVEL",
4897			     "Prefer [subsystem eg: netdev]_$level2([subsystem]dev, ... then dev_$level2(dev, ... then pr_$level(...  to $printk(KERN_$orig ...\n" . $herecurr);
4898		}
4899
4900# prefer dev_<level> to dev_printk(KERN_<LEVEL>
4901		if ($line =~ /\bdev_printk\s*\(\s*KERN_([A-Z]+)/) {
4902			my $orig = $1;
4903			my $level = lc($orig);
4904			$level = "warn" if ($level eq "warning");
4905			$level = "dbg" if ($level eq "debug");
4906			WARN("PREFER_DEV_LEVEL",
4907			     "Prefer dev_$level(... to dev_printk(KERN_$orig, ...\n" . $herecurr);
4908		}
4909
4910# trace_printk should not be used in production code.
4911		if ($line =~ /\b(trace_printk|trace_puts|ftrace_vprintk)\s*\(/) {
4912			WARN("TRACE_PRINTK",
4913			     "Do not use $1() in production code (this can be ignored if built only with a debug config option)\n" . $herecurr);
4914		}
4915
4916# ENOSYS means "bad syscall nr" and nothing else.  This will have a small
4917# number of false positives, but assembly files are not checked, so at
4918# least the arch entry code will not trigger this warning.
4919		if ($line =~ /\bENOSYS\b/) {
4920			WARN("ENOSYS",
4921			     "ENOSYS means 'invalid syscall nr' and nothing else\n" . $herecurr);
4922		}
4923
4924# ENOTSUPP is not a standard error code and should be avoided in new patches.
4925# Folks usually mean EOPNOTSUPP (also called ENOTSUP), when they type ENOTSUPP.
4926# Similarly to ENOSYS warning a small number of false positives is expected.
4927		if (!$file && $line =~ /\bENOTSUPP\b/) {
4928			if (WARN("ENOTSUPP",
4929				 "ENOTSUPP is not a SUSV4 error code, prefer EOPNOTSUPP\n" . $herecurr) &&
4930			    $fix) {
4931				$fixed[$fixlinenr] =~ s/\bENOTSUPP\b/EOPNOTSUPP/;
4932			}
4933		}
4934
4935# function brace can't be on same line, except for #defines of do while,
4936# or if closed on same line
4937		if ($perl_version_ok &&
4938		    $sline =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ &&
4939		    $sline !~ /\#\s*define\b.*do\s*\{/ &&
4940		    $sline !~ /}/) {
4941			if (ERROR("OPEN_BRACE",
4942				  "open brace '{' following function definitions go on the next line\n" . $herecurr) &&
4943			    $fix) {
4944				fix_delete_line($fixlinenr, $rawline);
4945				my $fixed_line = $rawline;
4946				$fixed_line =~ /(^..*$Type\s*$Ident\(.*\)\s*)\{(.*)$/;
4947				my $line1 = $1;
4948				my $line2 = $2;
4949				fix_insert_line($fixlinenr, ltrim($line1));
4950				fix_insert_line($fixlinenr, "\+{");
4951				if ($line2 !~ /^\s*$/) {
4952					fix_insert_line($fixlinenr, "\+\t" . trim($line2));
4953				}
4954			}
4955		}
4956
4957# open braces for enum, union and struct go on the same line.
4958		if ($line =~ /^.\s*{/ &&
4959		    $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) {
4960			if (ERROR("OPEN_BRACE",
4961				  "open brace '{' following $1 go on the same line\n" . $hereprev) &&
4962			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
4963				fix_delete_line($fixlinenr - 1, $prevrawline);
4964				fix_delete_line($fixlinenr, $rawline);
4965				my $fixedline = rtrim($prevrawline) . " {";
4966				fix_insert_line($fixlinenr, $fixedline);
4967				$fixedline = $rawline;
4968				$fixedline =~ s/^(.\s*)\{\s*/$1\t/;
4969				if ($fixedline !~ /^\+\s*$/) {
4970					fix_insert_line($fixlinenr, $fixedline);
4971				}
4972			}
4973		}
4974
4975# missing space after union, struct or enum definition
4976		if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) {
4977			if (WARN("SPACING",
4978				 "missing space after $1 definition\n" . $herecurr) &&
4979			    $fix) {
4980				$fixed[$fixlinenr] =~
4981				    s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/;
4982			}
4983		}
4984
4985# Function pointer declarations
4986# check spacing between type, funcptr, and args
4987# canonical declaration is "type (*funcptr)(args...)"
4988		if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) {
4989			my $declare = $1;
4990			my $pre_pointer_space = $2;
4991			my $post_pointer_space = $3;
4992			my $funcname = $4;
4993			my $post_funcname_space = $5;
4994			my $pre_args_space = $6;
4995
4996# the $Declare variable will capture all spaces after the type
4997# so check it for a missing trailing missing space but pointer return types
4998# don't need a space so don't warn for those.
4999			my $post_declare_space = "";
5000			if ($declare =~ /(\s+)$/) {
5001				$post_declare_space = $1;
5002				$declare = rtrim($declare);
5003			}
5004			if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) {
5005				WARN("SPACING",
5006				     "missing space after return type\n" . $herecurr);
5007				$post_declare_space = " ";
5008			}
5009
5010# unnecessary space "type  (*funcptr)(args...)"
5011# This test is not currently implemented because these declarations are
5012# equivalent to
5013#	int  foo(int bar, ...)
5014# and this is form shouldn't/doesn't generate a checkpatch warning.
5015#
5016#			elsif ($declare =~ /\s{2,}$/) {
5017#				WARN("SPACING",
5018#				     "Multiple spaces after return type\n" . $herecurr);
5019#			}
5020
5021# unnecessary space "type ( *funcptr)(args...)"
5022			if (defined $pre_pointer_space &&
5023			    $pre_pointer_space =~ /^\s/) {
5024				WARN("SPACING",
5025				     "Unnecessary space after function pointer open parenthesis\n" . $herecurr);
5026			}
5027
5028# unnecessary space "type (* funcptr)(args...)"
5029			if (defined $post_pointer_space &&
5030			    $post_pointer_space =~ /^\s/) {
5031				WARN("SPACING",
5032				     "Unnecessary space before function pointer name\n" . $herecurr);
5033			}
5034
5035# unnecessary space "type (*funcptr )(args...)"
5036			if (defined $post_funcname_space &&
5037			    $post_funcname_space =~ /^\s/) {
5038				WARN("SPACING",
5039				     "Unnecessary space after function pointer name\n" . $herecurr);
5040			}
5041
5042# unnecessary space "type (*funcptr) (args...)"
5043			if (defined $pre_args_space &&
5044			    $pre_args_space =~ /^\s/) {
5045				WARN("SPACING",
5046				     "Unnecessary space before function pointer arguments\n" . $herecurr);
5047			}
5048
5049			if (show_type("SPACING") && $fix) {
5050				$fixed[$fixlinenr] =~
5051				    s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex;
5052			}
5053		}
5054
5055# check for spacing round square brackets; allowed:
5056#  1. with a type on the left -- int [] a;
5057#  2. at the beginning of a line for slice initialisers -- [0...10] = 5,
5058#  3. inside a curly brace -- = { [0...10] = 5 }
5059		while ($line =~ /(.*?\s)\[/g) {
5060			my ($where, $prefix) = ($-[1], $1);
5061			if ($prefix !~ /$Type\s+$/ &&
5062			    ($where != 0 || $prefix !~ /^.\s+$/) &&
5063			    $prefix !~ /[{,:]\s+$/) {
5064				if (ERROR("BRACKET_SPACE",
5065					  "space prohibited before open square bracket '['\n" . $herecurr) &&
5066				    $fix) {
5067				    $fixed[$fixlinenr] =~
5068					s/^(\+.*?)\s+\[/$1\[/;
5069				}
5070			}
5071		}
5072
5073# check for spaces between functions and their parentheses.
5074		while ($line =~ /($Ident)\s+\(/g) {
5075			my $name = $1;
5076			my $ctx_before = substr($line, 0, $-[1]);
5077			my $ctx = "$ctx_before$name";
5078
5079			# Ignore those directives where spaces _are_ permitted.
5080			if ($name =~ /^(?:
5081				if|for|while|switch|return|case|
5082				volatile|__volatile__|
5083				__attribute__|format|__extension__|
5084				asm|__asm__|scoped_guard)$/x)
5085			{
5086			# cpp #define statements have non-optional spaces, ie
5087			# if there is a space between the name and the open
5088			# parenthesis it is simply not a parameter group.
5089			} elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) {
5090
5091			# cpp #elif statement condition may start with a (
5092			} elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) {
5093
5094			# If this whole things ends with a type its most
5095			# likely a typedef for a function.
5096			} elsif ($ctx =~ /$Type$/) {
5097
5098			} else {
5099				if (WARN("SPACING",
5100					 "space prohibited between function name and open parenthesis '('\n" . $herecurr) &&
5101					     $fix) {
5102					$fixed[$fixlinenr] =~
5103					    s/\b$name\s+\(/$name\(/;
5104				}
5105			}
5106		}
5107
5108# Check operator spacing.
5109		if (!($line=~/\#\s*include/)) {
5110			my $fixed_line = "";
5111			my $line_fixed = 0;
5112
5113			my $ops = qr{
5114				<<=|>>=|<=|>=|==|!=|
5115				\+=|-=|\*=|\/=|%=|\^=|\|=|&=|
5116				=>|->|<<|>>|<|>|=|!|~|
5117				&&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%|
5118				\?:|\?|:
5119			}x;
5120			my @elements = split(/($ops|;)/, $opline);
5121
5122##			print("element count: <" . $#elements . ">\n");
5123##			foreach my $el (@elements) {
5124##				print("el: <$el>\n");
5125##			}
5126
5127			my @fix_elements = ();
5128			my $off = 0;
5129
5130			foreach my $el (@elements) {
5131				push(@fix_elements, substr($rawline, $off, length($el)));
5132				$off += length($el);
5133			}
5134
5135			$off = 0;
5136
5137			my $blank = copy_spacing($opline);
5138			my $last_after = -1;
5139
5140			for (my $n = 0; $n < $#elements; $n += 2) {
5141
5142				my $good = $fix_elements[$n] . $fix_elements[$n + 1];
5143
5144##				print("n: <$n> good: <$good>\n");
5145
5146				$off += length($elements[$n]);
5147
5148				# Pick up the preceding and succeeding characters.
5149				my $ca = substr($opline, 0, $off);
5150				my $cc = '';
5151				if (length($opline) >= ($off + length($elements[$n + 1]))) {
5152					$cc = substr($opline, $off + length($elements[$n + 1]));
5153				}
5154				my $cb = "$ca$;$cc";
5155
5156				my $a = '';
5157				$a = 'V' if ($elements[$n] ne '');
5158				$a = 'W' if ($elements[$n] =~ /\s$/);
5159				$a = 'C' if ($elements[$n] =~ /$;$/);
5160				$a = 'B' if ($elements[$n] =~ /(\[|\()$/);
5161				$a = 'O' if ($elements[$n] eq '');
5162				$a = 'E' if ($ca =~ /^\s*$/);
5163
5164				my $op = $elements[$n + 1];
5165
5166				my $c = '';
5167				if (defined $elements[$n + 2]) {
5168					$c = 'V' if ($elements[$n + 2] ne '');
5169					$c = 'W' if ($elements[$n + 2] =~ /^\s/);
5170					$c = 'C' if ($elements[$n + 2] =~ /^$;/);
5171					$c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/);
5172					$c = 'O' if ($elements[$n + 2] eq '');
5173					$c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/);
5174				} else {
5175					$c = 'E';
5176				}
5177
5178				my $ctx = "${a}x${c}";
5179
5180				my $at = "(ctx:$ctx)";
5181
5182				my $ptr = substr($blank, 0, $off) . "^";
5183				my $hereptr = "$hereline$ptr\n";
5184
5185				# Pull out the value of this operator.
5186				my $op_type = substr($curr_values, $off + 1, 1);
5187
5188				# Get the full operator variant.
5189				my $opv = $op . substr($curr_vars, $off, 1);
5190
5191				# Ignore operators passed as parameters.
5192				if ($op_type ne 'V' &&
5193				    $ca =~ /\s$/ && $cc =~ /^\s*[,\)]/) {
5194
5195#				# Ignore comments
5196#				} elsif ($op =~ /^$;+$/) {
5197
5198				# ; should have either the end of line or a space or \ after it
5199				} elsif ($op eq ';') {
5200					if ($ctx !~ /.x[WEBC]/ &&
5201					    $cc !~ /^\\/ && $cc !~ /^;/) {
5202						if (ERROR("SPACING",
5203							  "space required after that '$op' $at\n" . $hereptr)) {
5204							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5205							$line_fixed = 1;
5206						}
5207					}
5208
5209				# // is a comment
5210				} elsif ($op eq '//') {
5211
5212				#   :   when part of a bitfield
5213				} elsif ($opv eq ':B') {
5214					# skip the bitfield test for now
5215
5216				# No spaces for:
5217				#   ->
5218				} elsif ($op eq '->') {
5219					if ($ctx =~ /Wx.|.xW/) {
5220						if (ERROR("SPACING",
5221							  "spaces prohibited around that '$op' $at\n" . $hereptr)) {
5222							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5223							if (defined $fix_elements[$n + 2]) {
5224								$fix_elements[$n + 2] =~ s/^\s+//;
5225							}
5226							$line_fixed = 1;
5227						}
5228					}
5229
5230				# , must not have a space before and must have a space on the right.
5231				} elsif ($op eq ',') {
5232					my $rtrim_before = 0;
5233					my $space_after = 0;
5234					if ($ctx =~ /Wx./) {
5235						if (ERROR("SPACING",
5236							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5237							$line_fixed = 1;
5238							$rtrim_before = 1;
5239						}
5240					}
5241					if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) {
5242						if (ERROR("SPACING",
5243							  "space required after that '$op' $at\n" . $hereptr)) {
5244							$line_fixed = 1;
5245							$last_after = $n;
5246							$space_after = 1;
5247						}
5248					}
5249					if ($rtrim_before || $space_after) {
5250						if ($rtrim_before) {
5251							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5252						} else {
5253							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5254						}
5255						if ($space_after) {
5256							$good .= " ";
5257						}
5258					}
5259
5260				# '*' as part of a type definition -- reported already.
5261				} elsif ($opv eq '*_') {
5262					#warn "'*' is part of type\n";
5263
5264				# unary operators should have a space before and
5265				# none after.  May be left adjacent to another
5266				# unary operator, or a cast
5267				} elsif ($op eq '!' || $op eq '~' ||
5268					 $opv eq '*U' || $opv eq '-U' ||
5269					 $opv eq '&U' || $opv eq '&&U') {
5270					if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) {
5271						if (ERROR("SPACING",
5272							  "space required before that '$op' $at\n" . $hereptr)) {
5273							if ($n != $last_after + 2) {
5274								$good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]);
5275								$line_fixed = 1;
5276							}
5277						}
5278					}
5279					if ($op eq '*' && $cc =~/\s*$Modifier\b/) {
5280						# A unary '*' may be const
5281
5282					} elsif ($ctx =~ /.xW/) {
5283						if (ERROR("SPACING",
5284							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5285							$good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]);
5286							if (defined $fix_elements[$n + 2]) {
5287								$fix_elements[$n + 2] =~ s/^\s+//;
5288							}
5289							$line_fixed = 1;
5290						}
5291					}
5292
5293				# unary ++ and unary -- are allowed no space on one side.
5294				} elsif ($op eq '++' or $op eq '--') {
5295					if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) {
5296						if (ERROR("SPACING",
5297							  "space required one side of that '$op' $at\n" . $hereptr)) {
5298							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " ";
5299							$line_fixed = 1;
5300						}
5301					}
5302					if ($ctx =~ /Wx[BE]/ ||
5303					    ($ctx =~ /Wx./ && $cc =~ /^;/)) {
5304						if (ERROR("SPACING",
5305							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5306							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5307							$line_fixed = 1;
5308						}
5309					}
5310					if ($ctx =~ /ExW/) {
5311						if (ERROR("SPACING",
5312							  "space prohibited after that '$op' $at\n" . $hereptr)) {
5313							$good = $fix_elements[$n] . trim($fix_elements[$n + 1]);
5314							if (defined $fix_elements[$n + 2]) {
5315								$fix_elements[$n + 2] =~ s/^\s+//;
5316							}
5317							$line_fixed = 1;
5318						}
5319					}
5320
5321				# << and >> may either have or not have spaces both sides
5322				} elsif ($op eq '<<' or $op eq '>>' or
5323					 $op eq '&' or $op eq '^' or $op eq '|' or
5324					 $op eq '+' or $op eq '-' or
5325					 $op eq '*' or $op eq '/' or
5326					 $op eq '%')
5327				{
5328					if ($check) {
5329						if (defined $fix_elements[$n + 2] && $ctx !~ /[EW]x[EW]/) {
5330							if (CHK("SPACING",
5331								"spaces preferred around that '$op' $at\n" . $hereptr)) {
5332								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5333								$fix_elements[$n + 2] =~ s/^\s+//;
5334								$line_fixed = 1;
5335							}
5336						} elsif (!defined $fix_elements[$n + 2] && $ctx !~ /Wx[OE]/) {
5337							if (CHK("SPACING",
5338								"space preferred before that '$op' $at\n" . $hereptr)) {
5339								$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]);
5340								$line_fixed = 1;
5341							}
5342						}
5343					} elsif ($ctx =~ /Wx[^WCE]|[^WCE]xW/) {
5344						if (ERROR("SPACING",
5345							  "need consistent spacing around '$op' $at\n" . $hereptr)) {
5346							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5347							if (defined $fix_elements[$n + 2]) {
5348								$fix_elements[$n + 2] =~ s/^\s+//;
5349							}
5350							$line_fixed = 1;
5351						}
5352					}
5353
5354				# A colon needs no spaces before when it is
5355				# terminating a case value or a label.
5356				} elsif ($opv eq ':C' || $opv eq ':L') {
5357					if ($ctx =~ /Wx./ and $realfile !~ m@.*\.lds\.h$@) {
5358						if (ERROR("SPACING",
5359							  "space prohibited before that '$op' $at\n" . $hereptr)) {
5360							$good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]);
5361							$line_fixed = 1;
5362						}
5363					}
5364
5365				# All the others need spaces both sides.
5366				} elsif ($ctx !~ /[EWC]x[CWE]/) {
5367					my $ok = 0;
5368
5369					# Ignore email addresses <foo@bar>
5370					if (($op eq '<' &&
5371					     $cc =~ /^\S+\@\S+>/) ||
5372					    ($op eq '>' &&
5373					     $ca =~ /<\S+\@\S+$/))
5374					{
5375						$ok = 1;
5376					}
5377
5378					# for asm volatile statements
5379					# ignore a colon with another
5380					# colon immediately before or after
5381					if (($op eq ':') &&
5382					    ($ca =~ /:$/ || $cc =~ /^:/)) {
5383						$ok = 1;
5384					}
5385
5386					# messages are ERROR, but ?: are CHK
5387					if ($ok == 0) {
5388						my $msg_level = \&ERROR;
5389						$msg_level = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/);
5390
5391						if (&{$msg_level}("SPACING",
5392								  "spaces required around that '$op' $at\n" . $hereptr)) {
5393							$good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " ";
5394							if (defined $fix_elements[$n + 2]) {
5395								$fix_elements[$n + 2] =~ s/^\s+//;
5396							}
5397							$line_fixed = 1;
5398						}
5399					}
5400				}
5401				$off += length($elements[$n + 1]);
5402
5403##				print("n: <$n> GOOD: <$good>\n");
5404
5405				$fixed_line = $fixed_line . $good;
5406			}
5407
5408			if (($#elements % 2) == 0) {
5409				$fixed_line = $fixed_line . $fix_elements[$#elements];
5410			}
5411
5412			if ($fix && $line_fixed && $fixed_line ne $fixed[$fixlinenr]) {
5413				$fixed[$fixlinenr] = $fixed_line;
5414			}
5415
5416
5417		}
5418
5419# check for whitespace before a non-naked semicolon
5420		if ($line =~ /^\+.*\S\s+;\s*$/) {
5421			if (WARN("SPACING",
5422				 "space prohibited before semicolon\n" . $herecurr) &&
5423			    $fix) {
5424				1 while $fixed[$fixlinenr] =~
5425				    s/^(\+.*\S)\s+;/$1;/;
5426			}
5427		}
5428
5429# check for multiple assignments
5430		if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) {
5431			CHK("MULTIPLE_ASSIGNMENTS",
5432			    "multiple assignments should be avoided\n" . $herecurr);
5433		}
5434
5435## # check for multiple declarations, allowing for a function declaration
5436## # continuation.
5437## 		if ($line =~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Ident.*/ &&
5438## 		    $line !~ /^.\s*$Type\s+$Ident(?:\s*=[^,{]*)?\s*,\s*$Type\s*$Ident.*/) {
5439##
5440## 			# Remove any bracketed sections to ensure we do not
5441## 			# falsely report the parameters of functions.
5442## 			my $ln = $line;
5443## 			while ($ln =~ s/\([^\(\)]*\)//g) {
5444## 			}
5445## 			if ($ln =~ /,/) {
5446## 				WARN("MULTIPLE_DECLARATION",
5447##				     "declaring multiple variables together should be avoided\n" . $herecurr);
5448## 			}
5449## 		}
5450
5451#need space before brace following if, while, etc
5452		if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) ||
5453		    $line =~ /\b(?:else|do)\{/) {
5454			if (ERROR("SPACING",
5455				  "space required before the open brace '{'\n" . $herecurr) &&
5456			    $fix) {
5457				$fixed[$fixlinenr] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/;
5458			}
5459		}
5460
5461## # check for blank lines before declarations
5462##		if ($line =~ /^.\t+$Type\s+$Ident(?:\s*=.*)?;/ &&
5463##		    $prevrawline =~ /^.\s*$/) {
5464##			WARN("SPACING",
5465##			     "No blank lines before declarations\n" . $hereprev);
5466##		}
5467##
5468
5469# closing brace should have a space following it when it has anything
5470# on the line
5471		if ($line =~ /}(?!(?:,|;|\)|\}))\S/) {
5472			if (ERROR("SPACING",
5473				  "space required after that close brace '}'\n" . $herecurr) &&
5474			    $fix) {
5475				$fixed[$fixlinenr] =~
5476				    s/}((?!(?:,|;|\)))\S)/} $1/;
5477			}
5478		}
5479
5480# check spacing on square brackets
5481		if ($line =~ /\[\s/ && $line !~ /\[\s*$/) {
5482			if (ERROR("SPACING",
5483				  "space prohibited after that open square bracket '['\n" . $herecurr) &&
5484			    $fix) {
5485				$fixed[$fixlinenr] =~
5486				    s/\[\s+/\[/;
5487			}
5488		}
5489		if ($line =~ /\s\]/) {
5490			if (ERROR("SPACING",
5491				  "space prohibited before that close square bracket ']'\n" . $herecurr) &&
5492			    $fix) {
5493				$fixed[$fixlinenr] =~
5494				    s/\s+\]/\]/;
5495			}
5496		}
5497
5498# check spacing on parentheses
5499		if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ &&
5500		    $line !~ /for\s*\(\s+;/) {
5501			if (ERROR("SPACING",
5502				  "space prohibited after that open parenthesis '('\n" . $herecurr) &&
5503			    $fix) {
5504				$fixed[$fixlinenr] =~
5505				    s/\(\s+/\(/;
5506			}
5507		}
5508		if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ &&
5509		    $line !~ /for\s*\(.*;\s+\)/ &&
5510		    $line !~ /:\s+\)/) {
5511			if (ERROR("SPACING",
5512				  "space prohibited before that close parenthesis ')'\n" . $herecurr) &&
5513			    $fix) {
5514				$fixed[$fixlinenr] =~
5515				    s/\s+\)/\)/;
5516			}
5517		}
5518
5519# check unnecessary parentheses around addressof/dereference single $Lvals
5520# ie: &(foo->bar) should be &foo->bar and *(foo->bar) should be *foo->bar
5521
5522		while ($line =~ /(?:[^&]&\s*|\*)\(\s*($Ident\s*(?:$Member\s*)+)\s*\)/g) {
5523			my $var = $1;
5524			if (CHK("UNNECESSARY_PARENTHESES",
5525				"Unnecessary parentheses around $var\n" . $herecurr) &&
5526			    $fix) {
5527				$fixed[$fixlinenr] =~ s/\(\s*\Q$var\E\s*\)/$var/;
5528			}
5529		}
5530
5531# check for unnecessary parentheses around function pointer uses
5532# ie: (foo->bar)(); should be foo->bar();
5533# but not "if (foo->bar) (" to avoid some false positives
5534		if ($line =~ /(\bif\s*|)(\(\s*$Ident\s*(?:$Member\s*)+\))[ \t]*\(/ && $1 !~ /^if/) {
5535			my $var = $2;
5536			if (CHK("UNNECESSARY_PARENTHESES",
5537				"Unnecessary parentheses around function pointer $var\n" . $herecurr) &&
5538			    $fix) {
5539				my $var2 = deparenthesize($var);
5540				$var2 =~ s/\s//g;
5541				$fixed[$fixlinenr] =~ s/\Q$var\E/$var2/;
5542			}
5543		}
5544
5545# check for unnecessary parentheses around comparisons
5546# except in drivers/staging
5547		if (($realfile !~ m@^(?:drivers/staging/)@) &&
5548		    $perl_version_ok && defined($stat) &&
5549		    $stat =~ /(^.\s*if\s*($balanced_parens))/) {
5550			my $if_stat = $1;
5551			my $test = substr($2, 1, -1);
5552			my $herectx;
5553			while ($test =~ /(?:^|[^\w\&\!\~])+\s*\(\s*([\&\!\~]?\s*$Lval\s*(?:$Compare\s*$FuncArg)?)\s*\)/g) {
5554				my $match = $1;
5555				# avoid parentheses around potential macro args
5556				next if ($match =~ /^\s*\w+\s*$/);
5557				if (!defined($herectx)) {
5558					$herectx = $here . "\n";
5559					my $cnt = statement_rawlines($if_stat);
5560					for (my $n = 0; $n < $cnt; $n++) {
5561						my $rl = raw_line($linenr, $n);
5562						$herectx .=  $rl . "\n";
5563						last if $rl =~ /^[ \+].*\{/;
5564					}
5565				}
5566				CHK("UNNECESSARY_PARENTHESES",
5567				    "Unnecessary parentheses around '$match'\n" . $herectx);
5568			}
5569		}
5570
5571# check that goto labels aren't indented (allow a single space indentation)
5572# and ignore bitfield definitions like foo:1
5573# Strictly, labels can have whitespace after the identifier and before the :
5574# but this is not allowed here as many ?: uses would appear to be labels
5575		if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
5576		    $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
5577		    $sline !~ /^.\s+default:/) {
5578			if (WARN("INDENTED_LABEL",
5579				 "labels should not be indented\n" . $herecurr) &&
5580			    $fix) {
5581				$fixed[$fixlinenr] =~
5582				    s/^(.)\s+/$1/;
5583			}
5584		}
5585
5586# check if a statement with a comma should be two statements like:
5587#	foo = bar(),	/* comma should be semicolon */
5588#	bar = baz();
5589		if (defined($stat) &&
5590		    $stat =~ /^\+\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*,\s*(?:$Lval\s*$Assignment\s*)?$FuncArg\s*;\s*$/) {
5591			my $cnt = statement_rawlines($stat);
5592			my $herectx = get_stat_here($linenr, $cnt, $here);
5593			WARN("SUSPECT_COMMA_SEMICOLON",
5594			     "Possible comma where semicolon could be used\n" . $herectx);
5595		}
5596
5597# return is not a function
5598		if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) {
5599			my $spacing = $1;
5600			if ($perl_version_ok &&
5601			    $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) {
5602				my $value = $1;
5603				$value = deparenthesize($value);
5604				if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) {
5605					ERROR("RETURN_PARENTHESES",
5606					      "return is not a function, parentheses are not required\n" . $herecurr);
5607				}
5608			} elsif ($spacing !~ /\s+/) {
5609				ERROR("SPACING",
5610				      "space required before the open parenthesis '('\n" . $herecurr);
5611			}
5612		}
5613
5614# unnecessary return in a void function
5615# at end-of-function, with the previous line a single leading tab, then return;
5616# and the line before that not a goto label target like "out:"
5617		if ($sline =~ /^[ \+]}\s*$/ &&
5618		    $prevline =~ /^\+\treturn\s*;\s*$/ &&
5619		    $linenr >= 3 &&
5620		    $lines[$linenr - 3] =~ /^[ +]/ &&
5621		    $lines[$linenr - 3] !~ /^[ +]\s*$Ident\s*:/) {
5622			WARN("RETURN_VOID",
5623			     "void function return statements are not generally useful\n" . $hereprev);
5624		}
5625
5626# if statements using unnecessary parentheses - ie: if ((foo == bar))
5627		if ($perl_version_ok &&
5628		    $line =~ /\bif\s*((?:\(\s*){2,})/) {
5629			my $openparens = $1;
5630			my $count = $openparens =~ tr@\(@\(@;
5631			my $msg = "";
5632			if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) {
5633				my $comp = $4;	#Not $1 because of $LvalOrFunc
5634				$msg = " - maybe == should be = ?" if ($comp eq "==");
5635				WARN("UNNECESSARY_PARENTHESES",
5636				     "Unnecessary parentheses$msg\n" . $herecurr);
5637			}
5638		}
5639
5640# comparisons with a constant or upper case identifier on the left
5641#	avoid cases like "foo + BAR < baz"
5642#	only fix matches surrounded by parentheses to avoid incorrect
5643#	conversions like "FOO < baz() + 5" being "misfixed" to "baz() > FOO + 5"
5644		if ($perl_version_ok &&
5645		    $line =~ /^\+(.*)\b($Constant|[A-Z_][A-Z0-9_]*)\s*($Compare)\s*($LvalOrFunc)/) {
5646			my $lead = $1;
5647			my $const = $2;
5648			my $comp = $3;
5649			my $to = $4;
5650			my $newcomp = $comp;
5651			if ($lead !~ /(?:$Operators|\.)\s*$/ &&
5652			    $to !~ /^(?:Constant|[A-Z_][A-Z0-9_]*)$/ &&
5653			    WARN("CONSTANT_COMPARISON",
5654				 "Comparisons should place the constant on the right side of the test\n" . $herecurr) &&
5655			    $fix) {
5656				if ($comp eq "<") {
5657					$newcomp = ">";
5658				} elsif ($comp eq "<=") {
5659					$newcomp = ">=";
5660				} elsif ($comp eq ">") {
5661					$newcomp = "<";
5662				} elsif ($comp eq ">=") {
5663					$newcomp = "<=";
5664				}
5665				$fixed[$fixlinenr] =~ s/\(\s*\Q$const\E\s*$Compare\s*\Q$to\E\s*\)/($to $newcomp $const)/;
5666			}
5667		}
5668
5669# Return of what appears to be an errno should normally be negative
5670		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
5671			my $name = $1;
5672			if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
5673				WARN("USE_NEGATIVE_ERRNO",
5674				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
5675			}
5676		}
5677
5678# Need a space before open parenthesis after if, while etc
5679		if ($line =~ /\b(if|while|for|switch)\(/) {
5680			if (ERROR("SPACING",
5681				  "space required before the open parenthesis '('\n" . $herecurr) &&
5682			    $fix) {
5683				$fixed[$fixlinenr] =~
5684				    s/\b(if|while|for|switch)\(/$1 \(/;
5685			}
5686		}
5687
5688# Check for illegal assignment in if conditional -- and check for trailing
5689# statements after the conditional.
5690		if ($line =~ /do\s*(?!{)/) {
5691			($stat, $cond, $line_nr_next, $remain_next, $off_next) =
5692				ctx_statement_block($linenr, $realcnt, 0)
5693					if (!defined $stat);
5694			my ($stat_next) = ctx_statement_block($line_nr_next,
5695						$remain_next, $off_next);
5696			$stat_next =~ s/\n./\n /g;
5697			##print "stat<$stat> stat_next<$stat_next>\n";
5698
5699			if ($stat_next =~ /^\s*while\b/) {
5700				# If the statement carries leading newlines,
5701				# then count those as offsets.
5702				my ($whitespace) =
5703					($stat_next =~ /^((?:\s*\n[+-])*\s*)/s);
5704				my $offset =
5705					statement_rawlines($whitespace) - 1;
5706
5707				$suppress_whiletrailers{$line_nr_next +
5708								$offset} = 1;
5709			}
5710		}
5711		if (!defined $suppress_whiletrailers{$linenr} &&
5712		    defined($stat) && defined($cond) &&
5713		    $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) {
5714			my ($s, $c) = ($stat, $cond);
5715			my $fixed_assign_in_if = 0;
5716
5717			if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) {
5718				if (ERROR("ASSIGN_IN_IF",
5719					  "do not use assignment in if condition\n" . $herecurr) &&
5720				    $fix && $perl_version_ok) {
5721					if ($rawline =~ /^\+(\s+)if\s*\(\s*(\!)?\s*\(\s*(($Lval)\s*=\s*$LvalOrFunc)\s*\)\s*(?:($Compare)\s*($FuncArg))?\s*\)\s*(\{)?\s*$/) {
5722						my $space = $1;
5723						my $not = $2;
5724						my $statement = $3;
5725						my $assigned = $4;
5726						my $test = $8;
5727						my $against = $9;
5728						my $brace = $15;
5729						fix_delete_line($fixlinenr, $rawline);
5730						fix_insert_line($fixlinenr, "$space$statement;");
5731						my $newline = "${space}if (";
5732						$newline .= '!' if defined($not);
5733						$newline .= '(' if (defined $not && defined($test) && defined($against));
5734						$newline .= "$assigned";
5735						$newline .= " $test $against" if (defined($test) && defined($against));
5736						$newline .= ')' if (defined $not && defined($test) && defined($against));
5737						$newline .= ')';
5738						$newline .= " {" if (defined($brace));
5739						fix_insert_line($fixlinenr + 1, $newline);
5740						$fixed_assign_in_if = 1;
5741					}
5742				}
5743			}
5744
5745			# Find out what is on the end of the line after the
5746			# conditional.
5747			substr($s, 0, length($c), '');
5748			$s =~ s/\n.*//g;
5749			$s =~ s/$;//g;	# Remove any comments
5750			if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ &&
5751			    $c !~ /}\s*while\s*/)
5752			{
5753				# Find out how long the conditional actually is.
5754				my @newlines = ($c =~ /\n/gs);
5755				my $cond_lines = 1 + $#newlines;
5756				my $stat_real = '';
5757
5758				$stat_real = raw_line($linenr, $cond_lines)
5759							. "\n" if ($cond_lines);
5760				if (defined($stat_real) && $cond_lines > 1) {
5761					$stat_real = "[...]\n$stat_real";
5762				}
5763
5764				if (ERROR("TRAILING_STATEMENTS",
5765					  "trailing statements should be on next line\n" . $herecurr . $stat_real) &&
5766				    !$fixed_assign_in_if &&
5767				    $cond_lines == 0 &&
5768				    $fix && $perl_version_ok &&
5769				    $fixed[$fixlinenr] =~ /^\+(\s*)((?:if|while|for)\s*$balanced_parens)\s*(.*)$/) {
5770					my $indent = $1;
5771					my $test = $2;
5772					my $rest = rtrim($4);
5773					if ($rest =~ /;$/) {
5774						$fixed[$fixlinenr] = "\+$indent$test";
5775						fix_insert_line($fixlinenr + 1, "$indent\t$rest");
5776					}
5777				}
5778			}
5779		}
5780
5781# Check for bitwise tests written as boolean
5782		if ($line =~ /
5783			(?:
5784				(?:\[|\(|\&\&|\|\|)
5785				\s*0[xX][0-9]+\s*
5786				(?:\&\&|\|\|)
5787			|
5788				(?:\&\&|\|\|)
5789				\s*0[xX][0-9]+\s*
5790				(?:\&\&|\|\||\)|\])
5791			)/x)
5792		{
5793			WARN("HEXADECIMAL_BOOLEAN_TEST",
5794			     "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr);
5795		}
5796
5797# if and else should not have general statements after it
5798		if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) {
5799			my $s = $1;
5800			$s =~ s/$;//g;	# Remove any comments
5801			if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) {
5802				ERROR("TRAILING_STATEMENTS",
5803				      "trailing statements should be on next line\n" . $herecurr);
5804			}
5805		}
5806# if should not continue a brace
5807		if ($line =~ /}\s*if\b/) {
5808			ERROR("TRAILING_STATEMENTS",
5809			      "trailing statements should be on next line (or did you mean 'else if'?)\n" .
5810				$herecurr);
5811		}
5812# case and default should not have general statements after them
5813		if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g &&
5814		    $line !~ /\G(?:
5815			(?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$|
5816			\s*return\s+
5817		    )/xg)
5818		{
5819			ERROR("TRAILING_STATEMENTS",
5820			      "trailing statements should be on next line\n" . $herecurr);
5821		}
5822
5823		# Check for }<nl>else {, these must be at the same
5824		# indent level to be relevant to each other.
5825		if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ &&
5826		    $previndent == $indent) {
5827			if (ERROR("ELSE_AFTER_BRACE",
5828				  "else should follow close brace '}'\n" . $hereprev) &&
5829			    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5830				fix_delete_line($fixlinenr - 1, $prevrawline);
5831				fix_delete_line($fixlinenr, $rawline);
5832				my $fixedline = $prevrawline;
5833				$fixedline =~ s/}\s*$//;
5834				if ($fixedline !~ /^\+\s*$/) {
5835					fix_insert_line($fixlinenr, $fixedline);
5836				}
5837				$fixedline = $rawline;
5838				$fixedline =~ s/^(.\s*)else/$1} else/;
5839				fix_insert_line($fixlinenr, $fixedline);
5840			}
5841		}
5842
5843		if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ &&
5844		    $previndent == $indent) {
5845			my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0);
5846
5847			# Find out what is on the end of the line after the
5848			# conditional.
5849			substr($s, 0, length($c), '');
5850			$s =~ s/\n.*//g;
5851
5852			if ($s =~ /^\s*;/) {
5853				if (ERROR("WHILE_AFTER_BRACE",
5854					  "while should follow close brace '}'\n" . $hereprev) &&
5855				    $fix && $prevline =~ /^\+/ && $line =~ /^\+/) {
5856					fix_delete_line($fixlinenr - 1, $prevrawline);
5857					fix_delete_line($fixlinenr, $rawline);
5858					my $fixedline = $prevrawline;
5859					my $trailing = $rawline;
5860					$trailing =~ s/^\+//;
5861					$trailing = trim($trailing);
5862					$fixedline =~ s/}\s*$/} $trailing/;
5863					fix_insert_line($fixlinenr, $fixedline);
5864				}
5865			}
5866		}
5867
5868#Specific variable tests
5869		while ($line =~ m{($Constant|$Lval)}g) {
5870			my $var = $1;
5871
5872#CamelCase
5873			if ($var !~ /^$Constant$/ &&
5874			    $var =~ /[A-Z][a-z]|[a-z][A-Z]/ &&
5875#Ignore C keywords
5876			    $var !~ /^_Generic$/ &&
5877#Ignore some autogenerated defines and enum values
5878			    $var !~ /^(?:[A-Z]+_){1,5}[A-Z]{1,3}[a-z]/ &&
5879#Ignore Page<foo> variants
5880			    $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ &&
5881#Ignore ETHTOOL_LINK_MODE_<foo> variants
5882			    $var !~ /^ETHTOOL_LINK_MODE_/ &&
5883#Ignore SI style variants like nS, mV and dB
5884#(ie: max_uV, regulator_min_uA_show, RANGE_mA_VALUE)
5885			    $var !~ /^(?:[a-z0-9_]*|[A-Z0-9_]*)?_?[a-z][A-Z](?:_[a-z0-9_]+|_[A-Z0-9_]+)?$/ &&
5886#Ignore some three character SI units explicitly, like MiB and KHz
5887			    $var !~ /^(?:[a-z_]*?)_?(?:[KMGT]iB|[KMGT]?Hz)(?:_[a-z_]+)?$/) {
5888				while ($var =~ m{\b($Ident)}g) {
5889					my $word = $1;
5890					next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/);
5891					if ($check) {
5892						seed_camelcase_includes();
5893						if (!$file && !$camelcase_file_seeded) {
5894							seed_camelcase_file($realfile);
5895							$camelcase_file_seeded = 1;
5896						}
5897					}
5898					if (!defined $camelcase{$word}) {
5899						$camelcase{$word} = 1;
5900						CHK("CAMELCASE",
5901						    "Avoid CamelCase: <$word>\n" . $herecurr);
5902					}
5903				}
5904			}
5905		}
5906
5907#no spaces allowed after \ in define
5908		if ($line =~ /\#\s*define.*\\\s+$/) {
5909			if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION",
5910				 "Whitespace after \\ makes next lines useless\n" . $herecurr) &&
5911			    $fix) {
5912				$fixed[$fixlinenr] =~ s/\s+$//;
5913			}
5914		}
5915
5916# warn if <asm/foo.h> is #included and <linux/foo.h> is available and includes
5917# itself <asm/foo.h> (uses RAW line)
5918		if ($tree && $rawline =~ m{^.\s*\#\s*include\s*\<asm\/(.*)\.h\>}) {
5919			my $file = "$1.h";
5920			my $checkfile = "include/linux/$file";
5921			if (-f "$root/$checkfile" &&
5922			    $realfile ne $checkfile &&
5923			    $1 !~ /$allowed_asm_includes/)
5924			{
5925				my $asminclude = `grep -Ec "#include\\s+<asm/$file>" $root/$checkfile`;
5926				if ($asminclude > 0) {
5927					if ($realfile =~ m{^arch/}) {
5928						CHK("ARCH_INCLUDE_LINUX",
5929						    "Consider using #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5930					} else {
5931						WARN("INCLUDE_LINUX",
5932						     "Use #include <linux/$file> instead of <asm/$file>\n" . $herecurr);
5933					}
5934				}
5935			}
5936		}
5937
5938# Usually multi-statement macros should be enclosed in a do {} while
5939# (0) loop.  Grab the first statement and ensure its the whole macro
5940# if its not enclosed in a known good container
5941		if ($realfile !~ m@/vmlinux.lds.h$@ &&
5942		    $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) {
5943			my $ln = $linenr;
5944			my $cnt = $realcnt;
5945			my ($off, $dstat, $dcond, $rest);
5946			my $ctx = '';
5947			my $has_flow_statement = 0;
5948			my $has_arg_concat = 0;
5949			($dstat, $dcond, $ln, $cnt, $off) =
5950				ctx_statement_block($linenr, $realcnt, 0);
5951			$ctx = $dstat;
5952			#print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n";
5953			#print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n";
5954
5955			$has_flow_statement = 1 if ($ctx =~ /\b(goto|return)\b/);
5956			$has_arg_concat = 1 if ($ctx =~ /\#\#/ && $ctx !~ /\#\#\s*(?:__VA_ARGS__|args)\b/);
5957
5958			$dstat =~ s/^.\s*\#\s*define\s+$Ident(\([^\)]*\))?\s*//;
5959			my $define_args = $1;
5960			my $define_stmt = $dstat;
5961			my @def_args = ();
5962
5963			if (defined $define_args && $define_args ne "") {
5964				$define_args = substr($define_args, 1, length($define_args) - 2);
5965				$define_args =~ s/\s*//g;
5966				$define_args =~ s/\\\+?//g;
5967				@def_args = split(",", $define_args);
5968			}
5969
5970			$dstat =~ s/$;//g;
5971			$dstat =~ s/\\\n.//g;
5972			$dstat =~ s/^\s*//s;
5973			$dstat =~ s/\s*$//s;
5974
5975			# Flatten any parentheses and braces
5976			while ($dstat =~ s/\([^\(\)]*\)/1u/ ||
5977			       $dstat =~ s/\{[^\{\}]*\}/1u/ ||
5978			       $dstat =~ s/.\[[^\[\]]*\]/1u/)
5979			{
5980			}
5981
5982			# Flatten any obvious string concatenation.
5983			while ($dstat =~ s/($String)\s*$Ident/$1/ ||
5984			       $dstat =~ s/$Ident\s*($String)/$1/)
5985			{
5986			}
5987
5988			# Make asm volatile uses seem like a generic function
5989			$dstat =~ s/\b_*asm_*\s+_*volatile_*\b/asm_volatile/g;
5990
5991			my $exceptions = qr{
5992				$Declare|
5993				# named exceptions
5994				module_param_named|
5995				MODULE_PARM_DESC|
5996				DECLARE_PER_CPU|
5997				DEFINE_PER_CPU|
5998				static_assert|
5999				# declaration primitives
6000				__typeof__\(|
6001				union|
6002				struct|
6003				\.$Ident\s*=\s*|
6004				^\"|\"$|
6005				^\[
6006			}x;
6007			#print "REST<$rest> dstat<$dstat> ctx<$ctx>\n";
6008
6009			$ctx =~ s/\n*$//;
6010			my $stmt_cnt = statement_rawlines($ctx);
6011			my $herectx = get_stat_here($linenr, $stmt_cnt, $here);
6012
6013			if ($dstat ne '' &&
6014			    $dstat !~ /^(?:$Ident|-?$Constant),$/ &&			# 10, // foo(),
6015			    $dstat !~ /^(?:$Ident|-?$Constant);$/ &&			# foo();
6016			    $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ &&		# 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz
6017			    $dstat !~ /^'X'$/ && $dstat !~ /^'XX'$/ &&			# character constants
6018			    $dstat !~ /$exceptions/ &&
6019			    $dstat !~ /^\.$Ident\s*=/ &&				# .foo =
6020			    $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ &&		# stringification #foo
6021			    $dstat !~ /^case\b/ &&					# case ...
6022			    $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ &&	# do {...} while (...); // do {...} while (...)
6023			    $dstat !~ /^while\s*$Constant\s*$Constant\s*$/ &&		# while (...) {...}
6024			    $dstat !~ /^for\s*$Constant$/ &&				# for (...)
6025			    $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ &&	# for (...) bar()
6026			    $dstat !~ /^do\s*{/ &&					# do {...
6027			    $dstat !~ /^\(\{/ &&						# ({...
6028			    $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/)
6029			{
6030				if ($dstat =~ /^\s*if\b/) {
6031					ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6032					      "Macros starting with if should be enclosed by a do - while loop to avoid possible if/else logic defects\n" . "$herectx");
6033				} elsif ($dstat =~ /;/) {
6034					WARN("MULTISTATEMENT_MACRO_USE_DO_WHILE",
6035					      "Non-declarative macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6036				} else {
6037					ERROR("COMPLEX_MACRO",
6038					      "Macros with complex values should be enclosed in parentheses\n" . "$herectx\nBUT SEE:\n$DO_WHILE_0_ADVICE");
6039				}
6040
6041			}
6042
6043			# Make $define_stmt single line, comment-free, etc
6044			my @stmt_array = split('\n', $define_stmt);
6045			my $first = 1;
6046			$define_stmt = "";
6047			foreach my $l (@stmt_array) {
6048				$l =~ s/\\$//;
6049				if ($first) {
6050					$define_stmt = $l;
6051					$first = 0;
6052				} elsif ($l =~ /^[\+ ]/) {
6053					$define_stmt .= substr($l, 1);
6054				}
6055			}
6056			$define_stmt =~ s/$;//g;
6057			$define_stmt =~ s/\s+/ /g;
6058			$define_stmt = trim($define_stmt);
6059
6060# check if any macro arguments are reused (ignore '...' and 'type')
6061			foreach my $arg (@def_args) {
6062			        next if ($arg =~ /\.\.\./);
6063			        next if ($arg =~ /^type$/i);
6064				my $tmp_stmt = $define_stmt;
6065				$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;
6066				$tmp_stmt =~ s/\#+\s*$arg\b//g;
6067				$tmp_stmt =~ s/\b$arg\s*\#\#//g;
6068				my $use_cnt = () = $tmp_stmt =~ /\b$arg\b/g;
6069				if ($use_cnt > 1) {
6070					CHK("MACRO_ARG_REUSE",
6071					    "Macro argument reuse '$arg' - possible side-effects?\n" . "$herectx");
6072				    }
6073# check if any macro arguments may have other precedence issues
6074				if ($tmp_stmt =~ m/($Operators)?\s*\b$arg\b\s*($Operators)?/m &&
6075				    ((defined($1) && $1 ne ',') ||
6076				     (defined($2) && $2 ne ','))) {
6077					CHK("MACRO_ARG_PRECEDENCE",
6078					    "Macro argument '$arg' may be better as '($arg)' to avoid precedence issues\n" . "$herectx");
6079				}
6080
6081# check if this is an unused argument
6082				if ($define_stmt !~ /\b$arg\b/ && $define_stmt) {
6083					WARN("MACRO_ARG_UNUSED",
6084					     "Argument '$arg' is not used in function-like macro\n" . "$herectx");
6085				}
6086			}
6087
6088# check for macros with flow control, but without ## concatenation
6089# ## concatenation is commonly a macro that defines a function so ignore those
6090			if ($has_flow_statement && !$has_arg_concat) {
6091				my $cnt = statement_rawlines($ctx);
6092				my $herectx = get_stat_here($linenr, $cnt, $here);
6093
6094				WARN("MACRO_WITH_FLOW_CONTROL",
6095				     "Macros with flow control statements should be avoided\n" . "$herectx");
6096			}
6097
6098# check for line continuations outside of #defines, preprocessor #, and asm
6099
6100		} elsif ($realfile =~ m@/vmlinux.lds.h$@) {
6101		    $line =~ s/(\w+)/$maybe_linker_symbol{$1}++/ge;
6102		    #print "REAL: $realfile\nln: $line\nkeys:", sort keys %maybe_linker_symbol;
6103		} else {
6104			if ($prevline !~ /^..*\\$/ &&
6105			    $line !~ /^\+\s*\#.*\\$/ &&		# preprocessor
6106			    $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ &&	# asm
6107			    $line =~ /^\+.*\\$/) {
6108				WARN("LINE_CONTINUATIONS",
6109				     "Avoid unnecessary line continuations\n" . $herecurr);
6110			}
6111		}
6112
6113# do {} while (0) macro tests:
6114# single-statement macros do not need to be enclosed in do while (0) loop,
6115# macro should not end with a semicolon
6116		if ($perl_version_ok &&
6117		    $realfile !~ m@/vmlinux.lds.h$@ &&
6118		    $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) {
6119			my $ln = $linenr;
6120			my $cnt = $realcnt;
6121			my ($off, $dstat, $dcond, $rest);
6122			my $ctx = '';
6123			($dstat, $dcond, $ln, $cnt, $off) =
6124				ctx_statement_block($linenr, $realcnt, 0);
6125			$ctx = $dstat;
6126
6127			$dstat =~ s/\\\n.//g;
6128			$dstat =~ s/$;/ /g;
6129
6130			if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) {
6131				my $stmts = $2;
6132				my $semis = $3;
6133
6134				$ctx =~ s/\n*$//;
6135				my $cnt = statement_rawlines($ctx);
6136				my $herectx = get_stat_here($linenr, $cnt, $here);
6137
6138				if (($stmts =~ tr/;/;/) == 1 &&
6139				    $stmts !~ /^\s*(if|while|for|switch)\b/) {
6140					WARN("SINGLE_STATEMENT_DO_WHILE_MACRO",
6141					     "Single statement macros should not use a do {} while (0) loop\n" . "$herectx");
6142				}
6143				if (defined $semis && $semis ne "") {
6144					WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON",
6145					     "do {} while (0) macros should not be semicolon terminated\n" . "$herectx");
6146				}
6147			} elsif ($dstat =~ /^\+\s*#\s*define\s+$Ident.*;\s*$/) {
6148				$ctx =~ s/\n*$//;
6149				my $cnt = statement_rawlines($ctx);
6150				my $herectx = get_stat_here($linenr, $cnt, $here);
6151
6152				WARN("TRAILING_SEMICOLON",
6153				     "macros should not use a trailing semicolon\n" . "$herectx");
6154			}
6155		}
6156
6157# check for redundant bracing round if etc
6158		if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) {
6159			my ($level, $endln, @chunks) =
6160				ctx_statement_full($linenr, $realcnt, 1);
6161			#print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n";
6162			#print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n";
6163			if ($#chunks > 0 && $level == 0) {
6164				my @allowed = ();
6165				my $allow = 0;
6166				my $seen = 0;
6167				my $herectx = $here . "\n";
6168				my $ln = $linenr - 1;
6169				for my $chunk (@chunks) {
6170					my ($cond, $block) = @{$chunk};
6171
6172					# If the condition carries leading newlines, then count those as offsets.
6173					my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s);
6174					my $offset = statement_rawlines($whitespace) - 1;
6175
6176					$allowed[$allow] = 0;
6177					#print "COND<$cond> whitespace<$whitespace> offset<$offset>\n";
6178
6179					# We have looked at and allowed this specific line.
6180					$suppress_ifbraces{$ln + $offset} = 1;
6181
6182					$herectx .= "$rawlines[$ln + $offset]\n[...]\n";
6183					$ln += statement_rawlines($block) - 1;
6184
6185					substr($block, 0, length($cond), '');
6186
6187					$seen++ if ($block =~ /^\s*{/);
6188
6189					#print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n";
6190					if (statement_lines($cond) > 1) {
6191						#print "APW: ALLOWED: cond<$cond>\n";
6192						$allowed[$allow] = 1;
6193					}
6194					if ($block =~/\b(?:if|for|while)\b/) {
6195						#print "APW: ALLOWED: block<$block>\n";
6196						$allowed[$allow] = 1;
6197					}
6198					if (statement_block_size($block) > 1) {
6199						#print "APW: ALLOWED: lines block<$block>\n";
6200						$allowed[$allow] = 1;
6201					}
6202					$allow++;
6203				}
6204				if ($seen) {
6205					my $sum_allowed = 0;
6206					foreach (@allowed) {
6207						$sum_allowed += $_;
6208					}
6209					if ($sum_allowed == 0) {
6210						WARN("BRACES",
6211						     "braces {} are not necessary for any arm of this statement\n" . $herectx);
6212					} elsif ($sum_allowed != $allow &&
6213						 $seen != $allow) {
6214						CHK("BRACES",
6215						    "braces {} should be used on all arms of this statement\n" . $herectx);
6216					}
6217				}
6218			}
6219		}
6220		if (!defined $suppress_ifbraces{$linenr - 1} &&
6221					$line =~ /\b(if|while|for|else)\b/) {
6222			my $allowed = 0;
6223
6224			# Check the pre-context.
6225			if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) {
6226				#print "APW: ALLOWED: pre<$1>\n";
6227				$allowed = 1;
6228			}
6229
6230			my ($level, $endln, @chunks) =
6231				ctx_statement_full($linenr, $realcnt, $-[0]);
6232
6233			# Check the condition.
6234			my ($cond, $block) = @{$chunks[0]};
6235			#print "CHECKING<$linenr> cond<$cond> block<$block>\n";
6236			if (defined $cond) {
6237				substr($block, 0, length($cond), '');
6238			}
6239			if (statement_lines($cond) > 1) {
6240				#print "APW: ALLOWED: cond<$cond>\n";
6241				$allowed = 1;
6242			}
6243			if ($block =~/\b(?:if|for|while)\b/) {
6244				#print "APW: ALLOWED: block<$block>\n";
6245				$allowed = 1;
6246			}
6247			if (statement_block_size($block) > 1) {
6248				#print "APW: ALLOWED: lines block<$block>\n";
6249				$allowed = 1;
6250			}
6251			# Check the post-context.
6252			if (defined $chunks[1]) {
6253				my ($cond, $block) = @{$chunks[1]};
6254				if (defined $cond) {
6255					substr($block, 0, length($cond), '');
6256				}
6257				if ($block =~ /^\s*\{/) {
6258					#print "APW: ALLOWED: chunk-1 block<$block>\n";
6259					$allowed = 1;
6260				}
6261			}
6262			if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) {
6263				my $cnt = statement_rawlines($block);
6264				my $herectx = get_stat_here($linenr, $cnt, $here);
6265
6266				WARN("BRACES",
6267				     "braces {} are not necessary for single statement blocks\n" . $herectx);
6268			}
6269		}
6270
6271# check for single line unbalanced braces
6272		if ($sline =~ /^.\s*\}\s*else\s*$/ ||
6273		    $sline =~ /^.\s*else\s*\{\s*$/) {
6274			CHK("BRACES", "Unbalanced braces around else statement\n" . $herecurr);
6275		}
6276
6277# check for unnecessary blank lines around braces
6278		if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) {
6279			if (CHK("BRACES",
6280				"Blank lines aren't necessary before a close brace '}'\n" . $hereprev) &&
6281			    $fix && $prevrawline =~ /^\+/) {
6282				fix_delete_line($fixlinenr - 1, $prevrawline);
6283			}
6284		}
6285		if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) {
6286			if (CHK("BRACES",
6287				"Blank lines aren't necessary after an open brace '{'\n" . $hereprev) &&
6288			    $fix) {
6289				fix_delete_line($fixlinenr, $rawline);
6290			}
6291		}
6292
6293# no volatiles please
6294		my $asm_volatile = qr{\b(__asm__|asm)\s+(__volatile__|volatile)\b};
6295		if ($line =~ /\bvolatile\b/ && $line !~ /$asm_volatile/) {
6296			WARN("VOLATILE",
6297			     "Use of volatile is usually wrong: see Documentation/process/volatile-considered-harmful.rst\n" . $herecurr);
6298		}
6299
6300# Check for user-visible strings broken across lines, which breaks the ability
6301# to grep for the string.  Make exceptions when the previous string ends in a
6302# newline (multiple lines in one string constant) or '\t', '\r', ';', or '{'
6303# (common in inline assembly) or is a octal \123 or hexadecimal \xaf value
6304		if ($line =~ /^\+\s*$String/ &&
6305		    $prevline =~ /"\s*$/ &&
6306		    $prevrawline !~ /(?:\\(?:[ntr]|[0-7]{1,3}|x[0-9a-fA-F]{1,2})|;\s*|\{\s*)"\s*$/) {
6307			if (WARN("SPLIT_STRING",
6308				 "quoted string split across lines\n" . $hereprev) &&
6309				     $fix &&
6310				     $prevrawline =~ /^\+.*"\s*$/ &&
6311				     $last_coalesced_string_linenr != $linenr - 1) {
6312				my $extracted_string = get_quoted_string($line, $rawline);
6313				my $comma_close = "";
6314				if ($rawline =~ /\Q$extracted_string\E(\s*\)\s*;\s*$|\s*,\s*)/) {
6315					$comma_close = $1;
6316				}
6317
6318				fix_delete_line($fixlinenr - 1, $prevrawline);
6319				fix_delete_line($fixlinenr, $rawline);
6320				my $fixedline = $prevrawline;
6321				$fixedline =~ s/"\s*$//;
6322				$fixedline .= substr($extracted_string, 1) . trim($comma_close);
6323				fix_insert_line($fixlinenr - 1, $fixedline);
6324				$fixedline = $rawline;
6325				$fixedline =~ s/\Q$extracted_string\E\Q$comma_close\E//;
6326				if ($fixedline !~ /\+\s*$/) {
6327					fix_insert_line($fixlinenr, $fixedline);
6328				}
6329				$last_coalesced_string_linenr = $linenr;
6330			}
6331		}
6332
6333# check for missing a space in a string concatenation
6334		if ($prevrawline =~ /[^\\]\w"$/ && $rawline =~ /^\+[\t ]+"\w/) {
6335			WARN('MISSING_SPACE',
6336			     "break quoted strings at a space character\n" . $hereprev);
6337		}
6338
6339# check for an embedded function name in a string when the function is known
6340# This does not work very well for -f --file checking as it depends on patch
6341# context providing the function name or a single line form for in-file
6342# function declarations
6343		if ($line =~ /^\+.*$String/ &&
6344		    defined($context_function) &&
6345		    get_quoted_string($line, $rawline) =~ /\b$context_function\b/ &&
6346		    length(get_quoted_string($line, $rawline)) != (length($context_function) + 2)) {
6347			WARN("EMBEDDED_FUNCTION_NAME",
6348			     "Prefer using '\"%s...\", __func__' to using '$context_function', this function's name, in a string\n" . $herecurr);
6349		}
6350
6351# check for unnecessary function tracing like uses
6352# This does not use $logFunctions because there are many instances like
6353# 'dprintk(FOO, "%s()\n", __func__);' which do not match $logFunctions
6354		if ($rawline =~ /^\+.*\([^"]*"$tracing_logging_tags{0,3}%s(?:\s*\(\s*\)\s*)?$tracing_logging_tags{0,3}(?:\\n)?"\s*,\s*__func__\s*\)\s*;/) {
6355			if (WARN("TRACING_LOGGING",
6356				 "Unnecessary ftrace-like logging - prefer using ftrace\n" . $herecurr) &&
6357			    $fix) {
6358                                fix_delete_line($fixlinenr, $rawline);
6359			}
6360		}
6361
6362# check for spaces before a quoted newline
6363		if ($rawline =~ /^.*\".*\s\\n/) {
6364			if (WARN("QUOTED_WHITESPACE_BEFORE_NEWLINE",
6365				 "unnecessary whitespace before a quoted newline\n" . $herecurr) &&
6366			    $fix) {
6367				$fixed[$fixlinenr] =~ s/^(\+.*\".*)\s+\\n/$1\\n/;
6368			}
6369
6370		}
6371
6372# concatenated string without spaces between elements
6373		if ($line =~ /$String[A-Z_]/ ||
6374		    ($line =~ /([A-Za-z0-9_]+)$String/ && $1 !~ /^[Lu]$/)) {
6375			if (CHK("CONCATENATED_STRING",
6376				"Concatenated strings should use spaces between elements\n" . $herecurr) &&
6377			    $fix) {
6378				while ($line =~ /($String)/g) {
6379					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6380					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E([A-Za-z0-9_])/$extracted_string $1/;
6381					$fixed[$fixlinenr] =~ s/([A-Za-z0-9_])\Q$extracted_string\E/$1 $extracted_string/;
6382				}
6383			}
6384		}
6385
6386# uncoalesced string fragments
6387		if ($line =~ /$String\s*[Lu]?"/) {
6388			if (WARN("STRING_FRAGMENTS",
6389				 "Consecutive strings are generally better as a single string\n" . $herecurr) &&
6390			    $fix) {
6391				while ($line =~ /($String)(?=\s*")/g) {
6392					my $extracted_string = substr($rawline, $-[0], $+[0] - $-[0]);
6393					$fixed[$fixlinenr] =~ s/\Q$extracted_string\E\s*"/substr($extracted_string, 0, -1)/e;
6394				}
6395			}
6396		}
6397
6398# check for non-standard and hex prefixed decimal printf formats
6399		my $show_L = 1;	#don't show the same defect twice
6400		my $show_Z = 1;
6401		while ($line =~ /(?:^|")([X\t]*)(?:"|$)/g) {
6402			my $string = substr($rawline, $-[1], $+[1] - $-[1]);
6403			$string =~ s/%%/__/g;
6404			# check for %L
6405			if ($show_L && $string =~ /%[\*\d\.\$]*L([diouxX])/) {
6406				WARN("PRINTF_L",
6407				     "\%L$1 is non-standard C, use %ll$1\n" . $herecurr);
6408				$show_L = 0;
6409			}
6410			# check for %Z
6411			if ($show_Z && $string =~ /%[\*\d\.\$]*Z([diouxX])/) {
6412				WARN("PRINTF_Z",
6413				     "%Z$1 is non-standard C, use %z$1\n" . $herecurr);
6414				$show_Z = 0;
6415			}
6416			# check for 0x<decimal>
6417			if ($string =~ /0x%[\*\d\.\$\Llzth]*[diou]/) {
6418				ERROR("PRINTF_0XDECIMAL",
6419				      "Prefixing 0x with decimal output is defective\n" . $herecurr);
6420			}
6421		}
6422
6423# check for line continuations in quoted strings with odd counts of "
6424		if ($rawline =~ /\\$/ && $sline =~ tr/"/"/ % 2) {
6425			WARN("LINE_CONTINUATIONS",
6426			     "Avoid line continuations in quoted strings\n" . $herecurr);
6427		}
6428
6429# warn about #if 0
6430		if ($line =~ /^.\s*\#\s*if\s+0\b/) {
6431			WARN("IF_0",
6432			     "Consider removing the code enclosed by this #if 0 and its #endif\n" . $herecurr);
6433		}
6434
6435# warn about #if 1
6436		if ($line =~ /^.\s*\#\s*if\s+1\b/) {
6437			WARN("IF_1",
6438			     "Consider removing the #if 1 and its #endif\n" . $herecurr);
6439		}
6440
6441# check for needless "if (<foo>) fn(<foo>)" uses
6442		if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) {
6443			my $tested = quotemeta($1);
6444			my $expr = '\s*\(\s*' . $tested . '\s*\)\s*;';
6445			if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?|(?:kmem_cache|mempool|dma_pool)_destroy)$expr/) {
6446				my $func = $1;
6447				if (WARN('NEEDLESS_IF',
6448					 "$func(NULL) is safe and this check is probably not required\n" . $hereprev) &&
6449				    $fix) {
6450					my $do_fix = 1;
6451					my $leading_tabs = "";
6452					my $new_leading_tabs = "";
6453					if ($lines[$linenr - 2] =~ /^\+(\t*)if\s*\(\s*$tested\s*\)\s*$/) {
6454						$leading_tabs = $1;
6455					} else {
6456						$do_fix = 0;
6457					}
6458					if ($lines[$linenr - 1] =~ /^\+(\t+)$func\s*\(\s*$tested\s*\)\s*;\s*$/) {
6459						$new_leading_tabs = $1;
6460						if (length($leading_tabs) + 1 ne length($new_leading_tabs)) {
6461							$do_fix = 0;
6462						}
6463					} else {
6464						$do_fix = 0;
6465					}
6466					if ($do_fix) {
6467						fix_delete_line($fixlinenr - 1, $prevrawline);
6468						$fixed[$fixlinenr] =~ s/^\+$new_leading_tabs/\+$leading_tabs/;
6469					}
6470				}
6471			}
6472		}
6473
6474# check for unnecessary "Out of Memory" messages
6475		if ($line =~ /^\+.*\b$logFunctions\s*\(/ &&
6476		    $prevline =~ /^[ \+]\s*if\s*\(\s*(\!\s*|NULL\s*==\s*)?($Lval)(\s*==\s*NULL\s*)?\s*\)/ &&
6477		    (defined $1 || defined $3) &&
6478		    $linenr > 3) {
6479			my $testval = $2;
6480			my $testline = $lines[$linenr - 3];
6481
6482			my ($s, $c) = ctx_statement_block($linenr - 3, $realcnt, 0);
6483#			print("line: <$line>\nprevline: <$prevline>\ns: <$s>\nc: <$c>\n\n\n");
6484
6485			if ($s =~ /(?:^|\n)[ \+]\s*(?:$Type\s*)?\Q$testval\E\s*=\s*(?:\([^\)]*\)\s*)?\s*$allocFunctions\s*\(/ &&
6486			    $s !~ /\b__GFP_NOWARN\b/ ) {
6487				WARN("OOM_MESSAGE",
6488				     "Possible unnecessary 'out of memory' message\n" . $hereprev);
6489			}
6490		}
6491
6492# check for logging functions with KERN_<LEVEL>
6493		if ($line !~ /printk(?:_ratelimited|_once)?\s*\(/ &&
6494		    $line =~ /\b$logFunctions\s*\(.*\b(KERN_[A-Z]+)\b/) {
6495			my $level = $1;
6496			if (WARN("UNNECESSARY_KERN_LEVEL",
6497				 "Possible unnecessary $level\n" . $herecurr) &&
6498			    $fix) {
6499				$fixed[$fixlinenr] =~ s/\s*$level\s*//;
6500			}
6501		}
6502
6503# check for logging continuations
6504		if ($line =~ /\bprintk\s*\(\s*KERN_CONT\b|\bpr_cont\s*\(/) {
6505			WARN("LOGGING_CONTINUATION",
6506			     "Avoid logging continuation uses where feasible\n" . $herecurr);
6507		}
6508
6509# check for unnecessary use of %h[xudi] and %hh[xudi] in logging functions
6510		if (defined $stat &&
6511		    $line =~ /\b$logFunctions\s*\(/ &&
6512		    index($stat, '"') >= 0) {
6513			my $lc = $stat =~ tr@\n@@;
6514			$lc = $lc + $linenr;
6515			my $stat_real = get_stat_real($linenr, $lc);
6516			pos($stat_real) = index($stat_real, '"');
6517			while ($stat_real =~ /[^\"%]*(%[\#\d\.\*\-]*(h+)[idux])/g) {
6518				my $pspec = $1;
6519				my $h = $2;
6520				my $lineoff = substr($stat_real, 0, $-[1]) =~ tr@\n@@;
6521				if (WARN("UNNECESSARY_MODIFIER",
6522					 "Integer promotion: Using '$h' in '$pspec' is unnecessary\n" . "$here\n$stat_real\n") &&
6523				    $fix && $fixed[$fixlinenr + $lineoff] =~ /^\+/) {
6524					my $nspec = $pspec;
6525					$nspec =~ s/h//g;
6526					$fixed[$fixlinenr + $lineoff] =~ s/\Q$pspec\E/$nspec/;
6527				}
6528			}
6529		}
6530
6531# check for mask then right shift without a parentheses
6532		if ($perl_version_ok &&
6533		    $line =~ /$LvalOrFunc\s*\&\s*($LvalOrFunc)\s*>>/ &&
6534		    $4 !~ /^\&/) { # $LvalOrFunc may be &foo, ignore if so
6535			WARN("MASK_THEN_SHIFT",
6536			     "Possible precedence defect with mask then right shift - may need parentheses\n" . $herecurr);
6537		}
6538
6539# check for pointer comparisons to NULL
6540		if ($perl_version_ok) {
6541			while ($line =~ /\b$LvalOrFunc\s*(==|\!=)\s*NULL\b/g) {
6542				my $val = $1;
6543				my $equal = "!";
6544				$equal = "" if ($4 eq "!=");
6545				if (CHK("COMPARISON_TO_NULL",
6546					"Comparison to NULL could be written \"${equal}${val}\"\n" . $herecurr) &&
6547					    $fix) {
6548					$fixed[$fixlinenr] =~ s/\b\Q$val\E\s*(?:==|\!=)\s*NULL\b/$equal$val/;
6549				}
6550			}
6551		}
6552
6553# check for bad placement of section $InitAttribute (e.g.: __initdata)
6554		if ($line =~ /(\b$InitAttribute\b)/) {
6555			my $attr = $1;
6556			if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) {
6557				my $ptr = $1;
6558				my $var = $2;
6559				if ((($ptr =~ /\b(union|struct)\s+$attr\b/ &&
6560				      ERROR("MISPLACED_INIT",
6561					    "$attr should be placed after $var\n" . $herecurr)) ||
6562				     ($ptr !~ /\b(union|struct)\s+$attr\b/ &&
6563				      WARN("MISPLACED_INIT",
6564					   "$attr should be placed after $var\n" . $herecurr))) &&
6565				    $fix) {
6566					$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;
6567				}
6568			}
6569		}
6570
6571# check for $InitAttributeData (ie: __initdata) with const
6572		if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) {
6573			my $attr = $1;
6574			$attr =~ /($InitAttributePrefix)(.*)/;
6575			my $attr_prefix = $1;
6576			my $attr_type = $2;
6577			if (ERROR("INIT_ATTRIBUTE",
6578				  "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) &&
6579			    $fix) {
6580				$fixed[$fixlinenr] =~
6581				    s/$InitAttributeData/${attr_prefix}initconst/;
6582			}
6583		}
6584
6585# check for $InitAttributeConst (ie: __initconst) without const
6586		if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) {
6587			my $attr = $1;
6588			if (ERROR("INIT_ATTRIBUTE",
6589				  "Use of $attr requires a separate use of const\n" . $herecurr) &&
6590			    $fix) {
6591				my $lead = $fixed[$fixlinenr] =~
6592				    /(^\+\s*(?:static\s+))/;
6593				$lead = rtrim($1);
6594				$lead = "$lead " if ($lead !~ /^\+$/);
6595				$lead = "${lead}const ";
6596				$fixed[$fixlinenr] =~ s/(^\+\s*(?:static\s+))/$lead/;
6597			}
6598		}
6599
6600# check for __read_mostly with const non-pointer (should just be const)
6601		if ($line =~ /\b__read_mostly\b/ &&
6602		    $line =~ /($Type)\s*$Ident/ && $1 !~ /\*\s*$/ && $1 =~ /\bconst\b/) {
6603			if (ERROR("CONST_READ_MOSTLY",
6604				  "Invalid use of __read_mostly with const type\n" . $herecurr) &&
6605			    $fix) {
6606				$fixed[$fixlinenr] =~ s/\s+__read_mostly\b//;
6607			}
6608		}
6609
6610# don't use __constant_<foo> functions outside of include/uapi/
6611		if ($realfile !~ m@^include/uapi/@ &&
6612		    $line =~ /(__constant_(?:htons|ntohs|[bl]e(?:16|32|64)_to_cpu|cpu_to_[bl]e(?:16|32|64)))\s*\(/) {
6613			my $constant_func = $1;
6614			my $func = $constant_func;
6615			$func =~ s/^__constant_//;
6616			if (WARN("CONSTANT_CONVERSION",
6617				 "$constant_func should be $func\n" . $herecurr) &&
6618			    $fix) {
6619				$fixed[$fixlinenr] =~ s/\b$constant_func\b/$func/g;
6620			}
6621		}
6622
6623# prefer usleep_range over udelay
6624		if ($line =~ /\budelay\s*\(\s*(\d+)\s*\)/) {
6625			my $delay = $1;
6626			# ignore udelay's < 10, however
6627			if (! ($delay < 10) ) {
6628				CHK("USLEEP_RANGE",
6629				    "usleep_range is preferred over udelay; see function description of usleep_range() and udelay().\n" . $herecurr);
6630			}
6631			if ($delay > 2000) {
6632				WARN("LONG_UDELAY",
6633				     "long udelay - prefer mdelay; see function description of mdelay().\n" . $herecurr);
6634			}
6635		}
6636
6637# warn about unexpectedly long msleep's
6638		if ($line =~ /\bmsleep\s*\((\d+)\);/) {
6639			if ($1 < 20) {
6640				WARN("MSLEEP",
6641				     "msleep < 20ms can sleep for up to 20ms; see function description of msleep().\n" . $herecurr);
6642			}
6643		}
6644
6645# check for comparisons of jiffies
6646		if ($line =~ /\bjiffies\s*$Compare|$Compare\s*jiffies\b/) {
6647			WARN("JIFFIES_COMPARISON",
6648			     "Comparing jiffies is almost always wrong; prefer time_after, time_before and friends\n" . $herecurr);
6649		}
6650
6651# check for comparisons of get_jiffies_64()
6652		if ($line =~ /\bget_jiffies_64\s*\(\s*\)\s*$Compare|$Compare\s*get_jiffies_64\s*\(\s*\)/) {
6653			WARN("JIFFIES_COMPARISON",
6654			     "Comparing get_jiffies_64() is almost always wrong; prefer time_after64, time_before64 and friends\n" . $herecurr);
6655		}
6656
6657# warn about #ifdefs in C files
6658#		if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) {
6659#			print "#ifdef in C files should be avoided\n";
6660#			print "$herecurr";
6661#			$clean = 0;
6662#		}
6663
6664# warn about spacing in #ifdefs
6665		if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) {
6666			if (ERROR("SPACING",
6667				  "exactly one space required after that #$1\n" . $herecurr) &&
6668			    $fix) {
6669				$fixed[$fixlinenr] =~
6670				    s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /;
6671			}
6672
6673		}
6674
6675# check for spinlock_t definitions without a comment.
6676		if ($line =~ /^.\s*(struct\s+mutex|spinlock_t)\s+\S+;/ ||
6677		    $line =~ /^.\s*(DEFINE_MUTEX)\s*\(/) {
6678			my $which = $1;
6679			if (!ctx_has_comment($first_line, $linenr)) {
6680				CHK("UNCOMMENTED_DEFINITION",
6681				    "$1 definition without comment\n" . $herecurr);
6682			}
6683		}
6684# check for memory barriers without a comment.
6685
6686		my $barriers = qr{
6687			mb|
6688			rmb|
6689			wmb
6690		}x;
6691		my $barrier_stems = qr{
6692			mb__before_atomic|
6693			mb__after_atomic|
6694			store_release|
6695			load_acquire|
6696			store_mb|
6697			(?:$barriers)
6698		}x;
6699		my $all_barriers = qr{
6700			(?:$barriers)|
6701			smp_(?:$barrier_stems)|
6702			virt_(?:$barrier_stems)
6703		}x;
6704
6705		if ($line =~ /\b(?:$all_barriers)\s*\(/) {
6706			if (!ctx_has_comment($first_line, $linenr)) {
6707				WARN("MEMORY_BARRIER",
6708				     "memory barrier without comment\n" . $herecurr);
6709			}
6710		}
6711
6712		my $underscore_smp_barriers = qr{__smp_(?:$barrier_stems)}x;
6713
6714		if ($realfile !~ m@^include/asm-generic/@ &&
6715		    $realfile !~ m@/barrier\.h$@ &&
6716		    $line =~ m/\b(?:$underscore_smp_barriers)\s*\(/ &&
6717		    $line !~ m/^.\s*\#\s*define\s+(?:$underscore_smp_barriers)\s*\(/) {
6718			WARN("MEMORY_BARRIER",
6719			     "__smp memory barriers shouldn't be used outside barrier.h and asm-generic\n" . $herecurr);
6720		}
6721
6722# check for waitqueue_active without a comment.
6723		if ($line =~ /\bwaitqueue_active\s*\(/) {
6724			if (!ctx_has_comment($first_line, $linenr)) {
6725				WARN("WAITQUEUE_ACTIVE",
6726				     "waitqueue_active without comment\n" . $herecurr);
6727			}
6728		}
6729
6730# check for data_race without a comment.
6731		if ($line =~ /\bdata_race\s*\(/) {
6732			if (!ctx_has_comment($first_line, $linenr)) {
6733				WARN("DATA_RACE",
6734				     "data_race without comment\n" . $herecurr);
6735			}
6736		}
6737
6738# check for context_unsafe without a comment.
6739		if ($line =~ /\bcontext_unsafe\b/ &&
6740		    !ctx_has_comment($first_line, $linenr)) {
6741			WARN("CONTEXT_UNSAFE",
6742			     "context_unsafe without comment\n" . $herecurr);
6743		}
6744
6745# check of hardware specific defines
6746		if ($line =~ m@^.\s*\#\s*if.*\b(__i386__|__powerpc64__|__sun__|__s390x__)\b@ && $realfile !~ m@include/asm-@) {
6747			CHK("ARCH_DEFINES",
6748			    "architecture specific defines should be avoided\n" .  $herecurr);
6749		}
6750
6751# check that the storage class is not after a type
6752		if ($line =~ /\b($Type)\s+($Storage)\b/) {
6753			WARN("STORAGE_CLASS",
6754			     "storage class '$2' should be located before type '$1'\n" . $herecurr);
6755		}
6756# Check that the storage class is at the beginning of a declaration
6757		if ($line =~ /\b$Storage\b/ &&
6758		    $line !~ /^.\s*$Storage/ &&
6759		    $line =~ /^.\s*(.+?)\$Storage\s/ &&
6760		    $1 !~ /[\,\)]\s*$/) {
6761			WARN("STORAGE_CLASS",
6762			     "storage class should be at the beginning of the declaration\n" . $herecurr);
6763		}
6764
6765# check the location of the inline attribute, that it is between
6766# storage class and type.
6767		if ($line =~ /\b$Type\s+$Inline\b/ ||
6768		    $line =~ /\b$Inline\s+$Storage\b/) {
6769			ERROR("INLINE_LOCATION",
6770			      "inline keyword should sit between storage class and type\n" . $herecurr);
6771		}
6772
6773# Check for __inline__ and __inline, prefer inline
6774		if ($realfile !~ m@\binclude/uapi/@ &&
6775		    $line =~ /\b(__inline__|__inline)\b/) {
6776			if (WARN("INLINE",
6777				 "plain inline is preferred over $1\n" . $herecurr) &&
6778			    $fix) {
6779				$fixed[$fixlinenr] =~ s/\b(__inline__|__inline)\b/inline/;
6780
6781			}
6782		}
6783
6784# Check for compiler attributes
6785		if ($realfile !~ m@\binclude/uapi/@ &&
6786		    $rawline =~ /\b__attribute__\s*\(\s*($balanced_parens)\s*\)/) {
6787			my $attr = $1;
6788			$attr =~ s/\s*\(\s*(.*)\)\s*/$1/;
6789
6790			my %attr_list = (
6791				"alias"				=> "__alias",
6792				"aligned"			=> "__aligned",
6793				"always_inline"			=> "__always_inline",
6794				"assume_aligned"		=> "__assume_aligned",
6795				"cold"				=> "__cold",
6796				"const"				=> "__attribute_const__",
6797				"copy"				=> "__copy",
6798				"designated_init"		=> "__designated_init",
6799				"externally_visible"		=> "__visible",
6800				"format"			=> "printf|scanf",
6801				"gnu_inline"			=> "__gnu_inline",
6802				"malloc"			=> "__malloc",
6803				"mode"				=> "__mode",
6804				"no_caller_saved_registers"	=> "__no_caller_saved_registers",
6805				"noclone"			=> "__noclone",
6806				"noinline"			=> "noinline",
6807				"nonstring"			=> "__nonstring",
6808				"noreturn"			=> "__noreturn",
6809				"packed"			=> "__packed",
6810				"pure"				=> "__pure",
6811				"section"			=> "__section",
6812				"used"				=> "__used",
6813				"weak"				=> "__weak"
6814			);
6815
6816			while ($attr =~ /\s*(\w+)\s*(${balanced_parens})?/g) {
6817				my $orig_attr = $1;
6818				my $params = '';
6819				$params = $2 if defined($2);
6820				my $curr_attr = $orig_attr;
6821				$curr_attr =~ s/^[\s_]+|[\s_]+$//g;
6822				if (exists($attr_list{$curr_attr})) {
6823					my $new = $attr_list{$curr_attr};
6824					if ($curr_attr eq "format" && $params) {
6825						$params =~ /^\s*\(\s*(\w+)\s*,\s*(.*)/;
6826						$new = "__$1\($2";
6827					} else {
6828						$new = "$new$params";
6829					}
6830					if (WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6831						 "Prefer $new over __attribute__(($orig_attr$params))\n" . $herecurr) &&
6832					    $fix) {
6833						my $remove = "\Q$orig_attr\E" . '\s*' . "\Q$params\E" . '(?:\s*,\s*)?';
6834						$fixed[$fixlinenr] =~ s/$remove//;
6835						$fixed[$fixlinenr] =~ s/\b__attribute__/$new __attribute__/;
6836						$fixed[$fixlinenr] =~ s/\}\Q$new\E/} $new/;
6837						$fixed[$fixlinenr] =~ s/ __attribute__\s*\(\s*\(\s*\)\s*\)//;
6838					}
6839				}
6840			}
6841
6842			# Check for __attribute__ unused, prefer __always_unused or __maybe_unused
6843			if ($attr =~ /^_*unused/) {
6844				WARN("PREFER_DEFINED_ATTRIBUTE_MACRO",
6845				     "__always_unused or __maybe_unused is preferred over __attribute__((__unused__))\n" . $herecurr);
6846			}
6847		}
6848
6849# Check for __attribute__ weak, or __weak declarations (may have link issues)
6850		if ($perl_version_ok &&
6851		    $line =~ /(?:$Declare|$DeclareMisordered)\s*$Ident\s*$balanced_parens\s*(?:$Attribute)?\s*;/ &&
6852		    ($line =~ /\b__attribute__\s*\(\s*\(.*\bweak\b/ ||
6853		     $line =~ /\b__weak\b/)) {
6854			ERROR("WEAK_DECLARATION",
6855			      "Using weak declarations can have unintended link defects\n" . $herecurr);
6856		}
6857
6858# check for c99 types like uint8_t used outside of uapi/ and tools/
6859		if ($realfile !~ m@\binclude/uapi/@ &&
6860		    $realfile !~ m@\btools/@ &&
6861		    $line =~ /\b($Declare)\s*$Ident\s*[=;,\[]/) {
6862			my $type = $1;
6863			if ($type =~ /\b($typeC99Typedefs)\b/) {
6864				$type = $1;
6865				my $kernel_type = 'u';
6866				$kernel_type = 's' if ($type =~ /^_*[si]/);
6867				$type =~ /(\d+)/;
6868				$kernel_type .= $1;
6869				if (CHK("PREFER_KERNEL_TYPES",
6870					"Prefer kernel type '$kernel_type' over '$type'\n" . $herecurr) &&
6871				    $fix) {
6872					$fixed[$fixlinenr] =~ s/\b$type\b/$kernel_type/;
6873				}
6874			}
6875		}
6876
6877# check for cast of C90 native int or longer types constants
6878		if ($line =~ /(\(\s*$C90_int_types\s*\)\s*)($Constant)\b/) {
6879			my $cast = $1;
6880			my $const = $2;
6881			my $suffix = "";
6882			my $newconst = $const;
6883			$newconst =~ s/${Int_type}$//;
6884			$suffix .= 'U' if ($cast =~ /\bunsigned\b/);
6885			if ($cast =~ /\blong\s+long\b/) {
6886			    $suffix .= 'LL';
6887			} elsif ($cast =~ /\blong\b/) {
6888			    $suffix .= 'L';
6889			}
6890			if (WARN("TYPECAST_INT_CONSTANT",
6891				 "Unnecessary typecast of c90 int constant - '$cast$const' could be '$const$suffix'\n" . $herecurr) &&
6892			    $fix) {
6893				$fixed[$fixlinenr] =~ s/\Q$cast\E$const\b/$newconst$suffix/;
6894			}
6895		}
6896
6897# check for sizeof(&)
6898		if ($line =~ /\bsizeof\s*\(\s*\&/) {
6899			WARN("SIZEOF_ADDRESS",
6900			     "sizeof(& should be avoided\n" . $herecurr);
6901		}
6902
6903# check for sizeof without parenthesis
6904		if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) {
6905			if (WARN("SIZEOF_PARENTHESIS",
6906				 "sizeof $1 should be sizeof($1)\n" . $herecurr) &&
6907			    $fix) {
6908				$fixed[$fixlinenr] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex;
6909			}
6910		}
6911
6912# check for struct spinlock declarations
6913		if ($line =~ /^.\s*\bstruct\s+spinlock\s+\w+\s*;/) {
6914			WARN("USE_SPINLOCK_T",
6915			     "struct spinlock should be spinlock_t\n" . $herecurr);
6916		}
6917
6918# check for seq_printf uses that could be seq_puts
6919		if ($sline =~ /\bseq_printf\s*\(.*"\s*\)\s*;\s*$/) {
6920			my $fmt = get_quoted_string($line, $rawline);
6921			$fmt =~ s/%%//g;
6922			if ($fmt !~ /%/) {
6923				if (WARN("PREFER_SEQ_PUTS",
6924					 "Prefer seq_puts to seq_printf\n" . $herecurr) &&
6925				    $fix) {
6926					$fixed[$fixlinenr] =~ s/\bseq_printf\b/seq_puts/;
6927				}
6928			}
6929		}
6930
6931# check for vsprintf extension %p<foo> misuses
6932		if ($perl_version_ok &&
6933		    defined $stat &&
6934		    $stat =~ /^\+(?![^\{]*\{\s*).*\b(\w+)\s*\(.*$String\s*,/s &&
6935		    $1 !~ /^_*volatile_*$/) {
6936			my $stat_real;
6937
6938			my $lc = $stat =~ tr@\n@@;
6939			$lc = $lc + $linenr;
6940		        for (my $count = $linenr; $count <= $lc; $count++) {
6941				my $specifier;
6942				my $extension;
6943				my $qualifier;
6944				my $bad_specifier = "";
6945				my $fmt = get_quoted_string($lines[$count - 1], raw_line($count, 0));
6946				$fmt =~ s/%%//g;
6947
6948				while ($fmt =~ /(\%[\*\d\.]*p(\w)(\w*))/g) {
6949					$specifier = $1;
6950					$extension = $2;
6951					$qualifier = $3;
6952					if ($extension !~ /[4SsBKRraEehMmIiUDdgVCbGNOxtf]/ ||
6953					    ($extension eq "f" &&
6954					     defined $qualifier && $qualifier !~ /^w/) ||
6955					    ($extension eq "4" &&
6956					     defined $qualifier && $qualifier !~ /^c(?:[hlbc]|hR)$/)) {
6957						$bad_specifier = $specifier;
6958						last;
6959					}
6960					if ($extension eq "x" && !defined($stat_real)) {
6961						if (!defined($stat_real)) {
6962							$stat_real = get_stat_real($linenr, $lc);
6963						}
6964						WARN("VSPRINTF_SPECIFIER_PX",
6965						     "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");
6966					}
6967				}
6968				if ($bad_specifier ne "") {
6969					my $stat_real = get_stat_real($linenr, $lc);
6970					my $msg_level = \&WARN;
6971					my $ext_type = "Invalid";
6972					my $use = "";
6973					if ($bad_specifier =~ /p[Ff]/) {
6974						$use = " - use %pS instead";
6975						$use =~ s/pS/ps/ if ($bad_specifier =~ /pf/);
6976					} elsif ($bad_specifier =~ /pA/) {
6977						$use =  " - '%pA' is only intended to be used from Rust code";
6978						$msg_level = \&ERROR;
6979					}
6980
6981					&{$msg_level}("VSPRINTF_POINTER_EXTENSION",
6982						      "$ext_type vsprintf pointer extension '$bad_specifier'$use\n" . "$here\n$stat_real\n");
6983				}
6984			}
6985		}
6986
6987# Check for misused memsets
6988		if ($perl_version_ok &&
6989		    defined $stat &&
6990		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/) {
6991
6992			my $ms_addr = $2;
6993			my $ms_val = $7;
6994			my $ms_size = $12;
6995
6996			if ($ms_size =~ /^(0x|)0$/i) {
6997				ERROR("MEMSET",
6998				      "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n");
6999			} elsif ($ms_size =~ /^(0x|)1$/i) {
7000				WARN("MEMSET",
7001				     "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n");
7002			}
7003		}
7004
7005# Check for memcpy(foo, bar, ETH_ALEN) that could be ether_addr_copy(foo, bar)
7006#		if ($perl_version_ok &&
7007#		    defined $stat &&
7008#		    $stat =~ /^\+(?:.*?)\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7009#			if (WARN("PREFER_ETHER_ADDR_COPY",
7010#				 "Prefer ether_addr_copy() over memcpy() if the Ethernet addresses are __aligned(2)\n" . "$here\n$stat\n") &&
7011#			    $fix) {
7012#				$fixed[$fixlinenr] =~ s/\bmemcpy\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/ether_addr_copy($2, $7)/;
7013#			}
7014#		}
7015
7016# Check for memcmp(foo, bar, ETH_ALEN) that could be ether_addr_equal*(foo, bar)
7017#		if ($perl_version_ok &&
7018#		    defined $stat &&
7019#		    $stat =~ /^\+(?:.*?)\bmemcmp\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7020#			WARN("PREFER_ETHER_ADDR_EQUAL",
7021#			     "Prefer ether_addr_equal() or ether_addr_equal_unaligned() over memcmp()\n" . "$here\n$stat\n")
7022#		}
7023
7024# check for memset(foo, 0x0, ETH_ALEN) that could be eth_zero_addr
7025# check for memset(foo, 0xFF, ETH_ALEN) that could be eth_broadcast_addr
7026#		if ($perl_version_ok &&
7027#		    defined $stat &&
7028#		    $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*ETH_ALEN\s*\)/) {
7029#
7030#			my $ms_val = $7;
7031#
7032#			if ($ms_val =~ /^(?:0x|)0+$/i) {
7033#				if (WARN("PREFER_ETH_ZERO_ADDR",
7034#					 "Prefer eth_zero_addr over memset()\n" . "$here\n$stat\n") &&
7035#				    $fix) {
7036#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_zero_addr($2)/;
7037#				}
7038#			} elsif ($ms_val =~ /^(?:0xff|255)$/i) {
7039#				if (WARN("PREFER_ETH_BROADCAST_ADDR",
7040#					 "Prefer eth_broadcast_addr() over memset()\n" . "$here\n$stat\n") &&
7041#				    $fix) {
7042#					$fixed[$fixlinenr] =~ s/\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*,\s*ETH_ALEN\s*\)/eth_broadcast_addr($2)/;
7043#				}
7044#			}
7045#		}
7046# strcpy uses that should likely be strscpy
7047		if ($line =~ /\bstrcpy\s*\(/ && !is_userspace($realfile)) {
7048			WARN("STRCPY",
7049			     "Prefer strscpy over strcpy - see: https://github.com/KSPP/linux/issues/88\n" . $herecurr);
7050		}
7051
7052# strlcpy uses that should likely be strscpy
7053		if ($line =~ /\bstrlcpy\s*\(/ && !is_userspace($realfile)) {
7054			WARN("STRLCPY",
7055			     "Prefer strscpy over strlcpy - see: https://github.com/KSPP/linux/issues/89\n" . $herecurr);
7056		}
7057
7058# strncpy uses that should likely be strscpy or strscpy_pad
7059		if ($line =~ /\bstrncpy\s*\(/ && !is_userspace($realfile)) {
7060			WARN("STRNCPY",
7061			     "Prefer strscpy, strscpy_pad, or __nonstring over strncpy - see: https://github.com/KSPP/linux/issues/90\n" . $herecurr);
7062		}
7063
7064# ethtool_sprintf uses that should likely be ethtool_puts
7065		if ($line =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7066			if (WARN("PREFER_ETHTOOL_PUTS",
7067				 "Prefer ethtool_puts over ethtool_sprintf with only two arguments\n" . $herecurr) &&
7068			    $fix) {
7069				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7070			}
7071		}
7072
7073		# use $rawline because $line loses %s via sanitization and thus we can't match against it.
7074		if ($rawline =~ /\bethtool_sprintf\s*\(\s*$FuncArg\s*,\s*\"\%s\"\s*,\s*$FuncArg\s*\)/) {
7075			if (WARN("PREFER_ETHTOOL_PUTS",
7076				 "Prefer ethtool_puts over ethtool_sprintf with standalone \"%s\" specifier\n" . $herecurr) &&
7077			    $fix) {
7078				$fixed[$fixlinenr] =~ s/\bethtool_sprintf\s*\(\s*($FuncArg)\s*,\s*"\%s"\s*,\s*($FuncArg)/ethtool_puts($1, $7)/;
7079			}
7080		}
7081
7082
7083# typecasts on min/max could be min_t/max_t
7084		if ($perl_version_ok &&
7085		    defined $stat &&
7086		    $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) {
7087			if (defined $2 || defined $7) {
7088				my $call = $1;
7089				my $cast1 = deparenthesize($2);
7090				my $arg1 = $3;
7091				my $cast2 = deparenthesize($7);
7092				my $arg2 = $8;
7093				my $cast;
7094
7095				if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) {
7096					$cast = "$cast1 or $cast2";
7097				} elsif ($cast1 ne "") {
7098					$cast = $cast1;
7099				} else {
7100					$cast = $cast2;
7101				}
7102				WARN("MINMAX",
7103				     "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n");
7104			}
7105		}
7106
7107# check usleep_range arguments
7108		if ($perl_version_ok &&
7109		    defined $stat &&
7110		    $stat =~ /^\+(?:.*?)\busleep_range\s*\(\s*($FuncArg)\s*,\s*($FuncArg)\s*\)/) {
7111			my $min = $1;
7112			my $max = $7;
7113			if ($min eq $max) {
7114				WARN("USLEEP_RANGE",
7115				     "usleep_range should not use min == max args;  see function description of usleep_range().\n" . "$here\n$stat\n");
7116			} elsif ($min =~ /^\d+$/ && $max =~ /^\d+$/ &&
7117				 $min > $max) {
7118				WARN("USLEEP_RANGE",
7119				     "usleep_range args reversed, use min then max;  see function description of usleep_range().\n" . "$here\n$stat\n");
7120			}
7121		}
7122
7123# check for naked sscanf
7124		if ($perl_version_ok &&
7125		    defined $stat &&
7126		    $line =~ /\bsscanf\b/ &&
7127		    ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ &&
7128		     $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ &&
7129		     $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) {
7130			my $lc = $stat =~ tr@\n@@;
7131			$lc = $lc + $linenr;
7132			my $stat_real = get_stat_real($linenr, $lc);
7133			WARN("NAKED_SSCANF",
7134			     "unchecked sscanf return value\n" . "$here\n$stat_real\n");
7135		}
7136
7137# check for simple sscanf that should be kstrto<foo>
7138		if ($perl_version_ok &&
7139		    defined $stat &&
7140		    $line =~ /\bsscanf\b/) {
7141			my $lc = $stat =~ tr@\n@@;
7142			$lc = $lc + $linenr;
7143			my $stat_real = get_stat_real($linenr, $lc);
7144			if ($stat_real =~ /\bsscanf\b\s*\(\s*$FuncArg\s*,\s*("[^"]+")/) {
7145				my $format = $6;
7146				my $count = $format =~ tr@%@%@;
7147				if ($count == 1 &&
7148				    $format =~ /^"\%(?i:ll[udxi]|[udxi]ll|ll|[hl]h?[udxi]|[udxi][hl]h?|[hl]h?|[udxi])"$/) {
7149					WARN("SSCANF_TO_KSTRTO",
7150					     "Prefer kstrto<type> to single variable sscanf\n" . "$here\n$stat_real\n");
7151				}
7152			}
7153		}
7154
7155# check for new externs in .h files.
7156		if ($realfile =~ /\.h$/ &&
7157		    $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) {
7158			if (CHK("AVOID_EXTERNS",
7159				"extern prototypes should be avoided in .h files\n" . $herecurr) &&
7160			    $fix) {
7161				$fixed[$fixlinenr] =~ s/(.*)\bextern\b\s*(.*)/$1$2/;
7162			}
7163		}
7164
7165# check for new externs in .c files.
7166		if ($realfile =~ /\.c$/ && defined $stat &&
7167		    $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s)
7168		{
7169			my $function_name = $1;
7170			my $paren_space = $2;
7171
7172			my $s = $stat;
7173			if (defined $cond) {
7174				substr($s, 0, length($cond), '');
7175			}
7176			if ($s =~ /^\s*;/)
7177			{
7178				WARN("AVOID_EXTERNS",
7179				     "externs should be avoided in .c files\n" .  $herecurr);
7180			}
7181
7182			if ($paren_space =~ /\n/) {
7183				WARN("FUNCTION_ARGUMENTS",
7184				     "arguments for function declarations should follow identifier\n" . $herecurr);
7185			}
7186
7187		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7188		    $stat =~ /^\+extern struct\s+(\w+)\s+(\w+)\[\];/)
7189		{
7190			my ($st_type, $st_name) = ($1, $2);
7191
7192			for my $s (keys %maybe_linker_symbol) {
7193			    #print "Linker symbol? $st_name : $s\n";
7194			    goto LIKELY_LINKER_SYMBOL
7195				if $st_name =~ /$s/;
7196			}
7197			WARN("AVOID_EXTERNS",
7198			     "found a file-scoped extern type:$st_type name:$st_name in .c file\n"
7199			     . "is this a linker symbol ?\n" . $herecurr);
7200		  LIKELY_LINKER_SYMBOL:
7201
7202		} elsif ($realfile =~ /\.c$/ && defined $stat &&
7203		    $stat =~ /^.\s*extern\s+/)
7204		{
7205			WARN("AVOID_EXTERNS",
7206			     "externs should be avoided in .c files\n" .  $herecurr);
7207		}
7208
7209# check for function declarations that have arguments without identifier names
7210		if (defined $stat &&
7211		    $stat =~ /^.\s*(?:extern\s+)?$Type\s*(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*\(\s*([^{]+)\s*\)\s*;/s &&
7212		    $1 ne "void") {
7213			my $args = trim($1);
7214			while ($args =~ m/\s*($Type\s*(?:$Ident|\(\s*\*\s*$Ident?\s*\)\s*$balanced_parens)?)/g) {
7215				my $arg = trim($1);
7216				if ($arg =~ /^$Type$/ && $arg !~ /enum\s+$Ident$/) {
7217					WARN("FUNCTION_ARGUMENTS",
7218					     "function definition argument '$arg' should also have an identifier name\n" . $herecurr);
7219				}
7220			}
7221		}
7222
7223# check for function definitions
7224		if ($perl_version_ok &&
7225		    defined $stat &&
7226		    $stat =~ /^.\s*(?:$Storage\s+)?$Type\s*($Ident)\s*$balanced_parens\s*{/s) {
7227			$context_function = $1;
7228
7229# check for multiline function definition with misplaced open brace
7230			my $ok = 0;
7231			my $cnt = statement_rawlines($stat);
7232			my $herectx = $here . "\n";
7233			for (my $n = 0; $n < $cnt; $n++) {
7234				my $rl = raw_line($linenr, $n);
7235				$herectx .=  $rl . "\n";
7236				$ok = 1 if ($rl =~ /^[ \+]\{/);
7237				$ok = 1 if ($rl =~ /\{/ && $n == 0);
7238				last if $rl =~ /^[ \+].*\{/;
7239			}
7240			if (!$ok) {
7241				ERROR("OPEN_BRACE",
7242				      "open brace '{' following function definitions go on the next line\n" . $herectx);
7243			}
7244		}
7245
7246# checks for new __setup's
7247		if ($rawline =~ /\b__setup\("([^"]*)"/) {
7248			my $name = $1;
7249
7250			if (!grep(/$name/, @setup_docs)) {
7251				CHK("UNDOCUMENTED_SETUP",
7252				    "__setup appears un-documented -- check Documentation/admin-guide/kernel-parameters.txt\n" . $herecurr);
7253			}
7254		}
7255
7256# check for pointless casting of alloc functions
7257		if ($line =~ /\*\s*\)\s*$allocFunctions\b/) {
7258			WARN("UNNECESSARY_CASTS",
7259			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
7260		}
7261
7262# alloc style
7263# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
7264		if ($perl_version_ok &&
7265		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k|v)[mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
7266			CHK("ALLOC_SIZEOF_STRUCT",
7267			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
7268		}
7269
7270# check for (kv|k)[mz]alloc that could be kmalloc_obj/kvmalloc_obj/kzalloc_obj/kvzalloc_obj
7271		if ($perl_version_ok &&
7272		    defined $stat &&
7273		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*,/) {
7274			my $oldfunc = $3;
7275			my $a1 = $4;
7276			my $newfunc = "kmalloc_obj";
7277			$newfunc = "kvmalloc_obj" if ($oldfunc eq "kvmalloc");
7278			$newfunc = "kvzalloc_obj" if ($oldfunc eq "kvzalloc");
7279			$newfunc = "kzalloc_obj" if ($oldfunc eq "kzalloc");
7280
7281			if ($a1 =~ s/^sizeof\s*\S\(?([^\)]*)\)?$/$1/) {
7282				my $cnt = statement_rawlines($stat);
7283				my $herectx = get_stat_here($linenr, $cnt, $here);
7284
7285				if (WARN("ALLOC_WITH_SIZEOF",
7286					 "Prefer $newfunc over $oldfunc with sizeof\n" . $herectx) &&
7287				    $cnt == 1 &&
7288				    $fix) {
7289					$fixed[$fixlinenr] =~ s/\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*,/$1 = $newfunc($a1,/;
7290				}
7291			}
7292		}
7293
7294
7295# check for (kv|k)[mz]alloc with multiplies that could be kmalloc_objs/kvmalloc_objs/kzalloc_objs/kvzalloc_objs
7296		if ($perl_version_ok &&
7297		    defined $stat &&
7298		    $stat =~ /^\+\s*($Lval)\s*\=\s*(?:$balanced_parens)?\s*((?:kv|k)[mz]alloc)\s*\(\s*($FuncArg)\s*\*\s*($FuncArg)\s*,/) {
7299			my $oldfunc = $3;
7300			my $a1 = $4;
7301			my $a2 = $10;
7302			my $newfunc = "kmalloc_objs";
7303			$newfunc = "kvmalloc_objs" if ($oldfunc eq "kvmalloc");
7304			$newfunc = "kvzalloc_objs" if ($oldfunc eq "kvzalloc");
7305			$newfunc = "kzalloc_objs" if ($oldfunc eq "kzalloc");
7306			my $r1 = $a1;
7307			my $r2 = $a2;
7308			if ($a1 =~ /^sizeof\s*\S/) {
7309				$r1 = $a2;
7310				$r2 = $a1;
7311			}
7312			if ($r1 !~ /^sizeof\b/ && $r2 =~ /^sizeof\s*\S/ &&
7313			    !($r1 =~ /^$Constant$/ || $r1 =~ /^[A-Z_][A-Z0-9_]*$/)) {
7314				my $cnt = statement_rawlines($stat);
7315				my $herectx = get_stat_here($linenr, $cnt, $here);
7316
7317				if (WARN("ALLOC_WITH_MULTIPLY",
7318					 "Prefer $newfunc over $oldfunc with multiply\n" . $herectx) &&
7319				    $cnt == 1 &&
7320				    $fix) {
7321					my $sized = trim($r2);
7322					$sized =~ s/^sizeof\s*\S\(?([^\)]*)\)?$/$1/;
7323					$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;
7324				}
7325			}
7326		}
7327
7328# check for krealloc arg reuse
7329		if ($perl_version_ok &&
7330		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*($Lval)\s*,/ &&
7331		    $1 eq $3) {
7332			WARN("KREALLOC_ARG_REUSE",
7333			     "Reusing the krealloc arg is almost always a bug\n" . $herecurr);
7334		}
7335
7336# check for alloc argument mismatch
7337		if ($line =~ /\b((?:devm_)?((?:k|kv)?(calloc|malloc_array)(?:_node)?))\s*\(\s*sizeof\b/) {
7338			WARN("ALLOC_ARRAY_ARGS",
7339			     "$1 uses number as first arg, sizeof is generally wrong\n" . $herecurr);
7340		}
7341
7342# check for multiple semicolons
7343		if ($line =~ /;\s*;\s*$/) {
7344			if (WARN("ONE_SEMICOLON",
7345				 "Statements terminations use 1 semicolon\n" . $herecurr) &&
7346			    $fix) {
7347				$fixed[$fixlinenr] =~ s/(\s*;\s*){2,}$/;/g;
7348			}
7349		}
7350
7351# check for #defines like: 1 << <digit> that could be BIT(digit), it is not exported to uapi
7352		if ($realfile !~ m@^include/uapi/@ &&
7353		    $line =~ /#\s*define\s+\w+\s+\(?\s*1\s*([ulUL]*)\s*\<\<\s*(?:\d+|$Ident)\s*\)?/) {
7354			my $ull = "";
7355			$ull = "_ULL" if (defined($1) && $1 =~ /ll/i);
7356			if (CHK("BIT_MACRO",
7357				"Prefer using the BIT$ull macro\n" . $herecurr) &&
7358			    $fix) {
7359				$fixed[$fixlinenr] =~ s/\(?\s*1\s*[ulUL]*\s*<<\s*(\d+|$Ident)\s*\)?/BIT${ull}($1)/;
7360			}
7361		}
7362
7363# check for IS_ENABLED() without CONFIG_<FOO> ($rawline for comments too)
7364		if ($rawline =~ /\bIS_ENABLED\s*\(\s*(\w+)\s*\)/ && $1 !~ /^${CONFIG_}/) {
7365			WARN("IS_ENABLED_CONFIG",
7366			     "IS_ENABLED($1) is normally used as IS_ENABLED(${CONFIG_}$1)\n" . $herecurr);
7367		}
7368
7369# check for #if defined CONFIG_<FOO> || defined CONFIG_<FOO>_MODULE
7370		if ($line =~ /^\+\s*#\s*if\s+defined(?:\s*\(?\s*|\s+)(${CONFIG_}[A-Z_]+)\s*\)?\s*\|\|\s*defined(?:\s*\(?\s*|\s+)\1_MODULE\s*\)?\s*$/) {
7371			my $config = $1;
7372			if (WARN("PREFER_IS_ENABLED",
7373				 "Prefer IS_ENABLED(<FOO>) to ${CONFIG_}<FOO> || ${CONFIG_}<FOO>_MODULE\n" . $herecurr) &&
7374			    $fix) {
7375				$fixed[$fixlinenr] = "\+#if IS_ENABLED($config)";
7376			}
7377		}
7378
7379# check for /* fallthrough */ like comment, prefer fallthrough;
7380		my @fallthroughs = (
7381			'fallthrough',
7382			'@fallthrough@',
7383			'lint -fallthrough[ \t]*',
7384			'intentional(?:ly)?[ \t]*fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)',
7385			'(?:else,?\s*)?FALL(?:S | |-)?THR(?:OUGH|U|EW)[ \t.!]*(?:-[^\n\r]*)?',
7386			'Fall(?:(?:s | |-)[Tt]|t)hr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7387			'fall(?:s | |-)?thr(?:ough|u|ew)[ \t.!]*(?:-[^\n\r]*)?',
7388		    );
7389		if ($raw_comment ne '') {
7390			foreach my $ft (@fallthroughs) {
7391				if ($raw_comment =~ /$ft/) {
7392					my $msg_level = \&WARN;
7393					$msg_level = \&CHK if ($file);
7394					&{$msg_level}("PREFER_FALLTHROUGH",
7395						      "Prefer 'fallthrough;' over fallthrough comment\n" . $herecurr);
7396					last;
7397				}
7398			}
7399		}
7400
7401# check for switch/default statements without a break;
7402		if ($perl_version_ok &&
7403		    defined $stat &&
7404		    $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) {
7405			my $cnt = statement_rawlines($stat);
7406			my $herectx = get_stat_here($linenr, $cnt, $here);
7407
7408			WARN("DEFAULT_NO_BREAK",
7409			     "switch default: should use break\n" . $herectx);
7410		}
7411
7412# check for gcc specific __FUNCTION__
7413		if ($line =~ /\b__FUNCTION__\b/) {
7414			if (WARN("USE_FUNC",
7415				 "__func__ should be used instead of gcc specific __FUNCTION__\n"  . $herecurr) &&
7416			    $fix) {
7417				$fixed[$fixlinenr] =~ s/\b__FUNCTION__\b/__func__/g;
7418			}
7419		}
7420
7421# check for uses of __DATE__, __TIME__, __TIMESTAMP__
7422		while ($line =~ /\b(__(?:DATE|TIME|TIMESTAMP)__)\b/g) {
7423			ERROR("DATE_TIME",
7424			      "Use of the '$1' macro makes the build non-deterministic\n" . $herecurr);
7425		}
7426
7427# check for use of yield()
7428		if ($line =~ /\byield\s*\(\s*\)/) {
7429			WARN("YIELD",
7430			     "Using yield() is generally wrong. See yield() kernel-doc (sched/core.c)\n"  . $herecurr);
7431		}
7432
7433# check for comparisons against true and false
7434		if ($line =~ /\+\s*(.*?)\b(true|false|$Lval)\s*(==|\!=)\s*(true|false|$Lval)\b(.*)$/i) {
7435			my $lead = $1;
7436			my $arg = $2;
7437			my $test = $3;
7438			my $otype = $4;
7439			my $trail = $5;
7440			my $op = "!";
7441
7442			($arg, $otype) = ($otype, $arg) if ($arg =~ /^(?:true|false)$/i);
7443
7444			my $type = lc($otype);
7445			if ($type =~ /^(?:true|false)$/) {
7446				if (("$test" eq "==" && "$type" eq "true") ||
7447				    ("$test" eq "!=" && "$type" eq "false")) {
7448					$op = "";
7449				}
7450
7451				CHK("BOOL_COMPARISON",
7452				    "Using comparison to $otype is error prone\n" . $herecurr);
7453
7454## maybe suggesting a correct construct would better
7455##				    "Using comparison to $otype is error prone.  Perhaps use '${lead}${op}${arg}${trail}'\n" . $herecurr);
7456
7457			}
7458		}
7459
7460# check for semaphores initialized locked
7461		if ($line =~ /^.\s*sema_init.+,\W?0\W?\)/) {
7462			WARN("CONSIDER_COMPLETION",
7463			     "consider using a completion\n" . $herecurr);
7464		}
7465
7466# recommend kstrto* over simple_strto* and strict_strto*
7467		if ($line =~ /\b((simple|strict)_(strto(l|ll|ul|ull)))\s*\(/) {
7468			WARN("CONSIDER_KSTRTO",
7469			     "$1 is obsolete, use k$3 instead\n" . $herecurr);
7470		}
7471
7472# check for __initcall(), use device_initcall() explicitly or more appropriate function please
7473		if ($line =~ /^.\s*__initcall\s*\(/) {
7474			WARN("USE_DEVICE_INITCALL",
7475			     "please use device_initcall() or more appropriate function instead of __initcall() (see include/linux/init.h)\n" . $herecurr);
7476		}
7477
7478# check for spin_is_locked(), suggest lockdep instead
7479		if ($line =~ /\bspin_is_locked\(/) {
7480			WARN("USE_LOCKDEP",
7481			     "Where possible, use lockdep_assert_held instead of assertions based on spin_is_locked\n" . $herecurr);
7482		}
7483
7484# check for deprecated apis
7485		if ($line =~ /\b($deprecated_apis_search)\b\s*\(/) {
7486			my $deprecated_api = $1;
7487			my $new_api = $deprecated_apis{$deprecated_api};
7488			WARN("DEPRECATED_API",
7489			     "Deprecated use of '$deprecated_api', prefer '$new_api' instead\n" . $herecurr);
7490		}
7491
7492# check for various structs that are normally const (ops, kgdb, device_tree)
7493# and avoid what seem like struct definitions 'struct foo {'
7494		if (defined($const_structs) &&
7495		    $line !~ /\bconst\b/ &&
7496		    $line =~ /\bstruct\s+($const_structs)\b(?!\s*\{)/) {
7497			WARN("CONST_STRUCT",
7498			     "struct $1 should normally be const\n" . $herecurr);
7499		}
7500
7501# use of NR_CPUS is usually wrong
7502# ignore definitions of NR_CPUS and usage to define arrays as likely right
7503# ignore designated initializers using NR_CPUS
7504		if ($line =~ /\bNR_CPUS\b/ &&
7505		    $line !~ /^.\s*\s*#\s*if\b.*\bNR_CPUS\b/ &&
7506		    $line !~ /^.\s*\s*#\s*define\b.*\bNR_CPUS\b/ &&
7507		    $line !~ /^.\s*$Declare\s.*\[[^\]]*NR_CPUS[^\]]*\]/ &&
7508		    $line !~ /\[[^\]]*\.\.\.[^\]]*NR_CPUS[^\]]*\]/ &&
7509		    $line !~ /\[[^\]]*NR_CPUS[^\]]*\.\.\.[^\]]*\]/ &&
7510		    $line !~ /^.\s*\.\w+\s*=\s*.*\bNR_CPUS\b/)
7511		{
7512			WARN("NR_CPUS",
7513			     "usage of NR_CPUS is often wrong - consider using cpu_possible(), num_possible_cpus(), for_each_possible_cpu(), etc\n" . $herecurr);
7514		}
7515
7516# Use of __ARCH_HAS_<FOO> or ARCH_HAVE_<BAR> is wrong.
7517		if ($line =~ /\+\s*#\s*define\s+((?:__)?ARCH_(?:HAS|HAVE)\w*)\b/) {
7518			ERROR("DEFINE_ARCH_HAS",
7519			      "#define of '$1' is wrong - use Kconfig variables or standard guards instead\n" . $herecurr);
7520		}
7521
7522# likely/unlikely comparisons similar to "(likely(foo) > 0)"
7523		if ($perl_version_ok &&
7524		    $line =~ /\b((?:un)?likely)\s*\(\s*$FuncArg\s*\)\s*$Compare/) {
7525			WARN("LIKELY_MISUSE",
7526			     "Using $1 should generally have parentheses around the comparison\n" . $herecurr);
7527		}
7528
7529# return sysfs_emit(foo, fmt, ...) fmt without newline
7530		if ($line =~ /\breturn\s+sysfs_emit\s*\(\s*$FuncArg\s*,\s*($String)/ &&
7531		    substr($rawline, $-[6], $+[6] - $-[6]) !~ /\\n"$/) {
7532			my $offset = $+[6] - 1;
7533			if (WARN("SYSFS_EMIT",
7534				 "return sysfs_emit(...) formats should include a terminating newline\n" . $herecurr) &&
7535			    $fix) {
7536				substr($fixed[$fixlinenr], $offset, 0) = '\\n';
7537			}
7538		}
7539
7540# check for array definition/declarations that should use flexible arrays instead
7541		if ($sline =~ /^[\+ ]\s*\}(?:\s*__packed)?\s*;\s*$/ &&
7542		    $prevline =~ /^\+\s*(?:\}(?:\s*__packed\s*)?|$Type)\s*$Ident\s*\[\s*(0|1)\s*\]\s*;\s*$/) {
7543			if (ERROR("FLEXIBLE_ARRAY",
7544				  "Use C99 flexible arrays - see https://docs.kernel.org/process/deprecated.html#zero-length-and-one-element-arrays\n" . $hereprev) &&
7545			    $1 == '0' && $fix) {
7546				$fixed[$fixlinenr - 1] =~ s/\[\s*0\s*\]/[]/;
7547			}
7548		}
7549
7550# nested likely/unlikely calls
7551		if ($line =~ /\b(?:(?:un)?likely)\s*\(\s*!?\s*(IS_ERR(?:_OR_NULL|_VALUE)?|WARN)/) {
7552			WARN("LIKELY_MISUSE",
7553			     "nested (un)?likely() calls, $1 already uses unlikely() internally\n" . $herecurr);
7554		}
7555
7556# whine mightly about in_atomic
7557		if ($line =~ /\bin_atomic\s*\(/) {
7558			if ($realfile =~ m@^drivers/@) {
7559				ERROR("IN_ATOMIC",
7560				      "do not use in_atomic in drivers\n" . $herecurr);
7561			} elsif ($realfile !~ m@^kernel/@) {
7562				WARN("IN_ATOMIC",
7563				     "use of in_atomic() is incorrect outside core kernel code\n" . $herecurr);
7564			}
7565		}
7566
7567# Complain about RCU Tasks Trace used outside of BPF (and of course, RCU).
7568		our $rcu_trace_funcs = qr{(?x:
7569			rcu_read_lock_trace |
7570			rcu_read_lock_trace_held |
7571			rcu_read_unlock_trace |
7572			call_rcu_tasks_trace |
7573			synchronize_rcu_tasks_trace |
7574			rcu_barrier_tasks_trace |
7575			rcu_request_urgent_qs_task
7576		)};
7577		our $rcu_trace_paths = qr{(?x:
7578			kernel/bpf/ |
7579			include/linux/bpf |
7580			net/bpf/ |
7581			kernel/rcu/ |
7582			include/linux/rcu
7583		)};
7584		if ($line =~ /\b($rcu_trace_funcs)\s*\(/) {
7585			if ($realfile !~ m{^$rcu_trace_paths}) {
7586				WARN("RCU_TASKS_TRACE",
7587				     "use of RCU tasks trace is incorrect outside BPF or core RCU code\n" . $herecurr);
7588			}
7589		}
7590
7591# check for lockdep_set_novalidate_class
7592		if ($line =~ /^.\s*lockdep_set_novalidate_class\s*\(/ ||
7593		    $line =~ /__lockdep_no_validate__\s*\)/ ) {
7594			if ($realfile !~ m@^kernel/lockdep@ &&
7595			    $realfile !~ m@^include/linux/lockdep@ &&
7596			    $realfile !~ m@^drivers/base/core@) {
7597				ERROR("LOCKDEP",
7598				      "lockdep_no_validate class is reserved for device->mutex.\n" . $herecurr);
7599			}
7600		}
7601
7602		if ($line =~ /debugfs_create_\w+.*\b$mode_perms_world_writable\b/ ||
7603		    $line =~ /DEVICE_ATTR.*\b$mode_perms_world_writable\b/) {
7604			WARN("EXPORTED_WORLD_WRITABLE",
7605			     "Exporting world writable files is usually an error. Consider more restrictive permissions.\n" . $herecurr);
7606		}
7607
7608# check for DEVICE_ATTR uses that could be DEVICE_ATTR_<FOO>
7609# and whether or not function naming is typical and if
7610# DEVICE_ATTR permissions uses are unusual too
7611		if ($perl_version_ok &&
7612		    defined $stat &&
7613		    $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*\)/) {
7614			my $var = $1;
7615			my $perms = $2;
7616			my $show = $3;
7617			my $store = $4;
7618			my $octal_perms = perms_to_octal($perms);
7619			if ($show =~ /^${var}_show$/ &&
7620			    $store =~ /^${var}_store$/ &&
7621			    $octal_perms eq "0644") {
7622				if (WARN("DEVICE_ATTR_RW",
7623					 "Use DEVICE_ATTR_RW\n" . $herecurr) &&
7624				    $fix) {
7625					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*$store\s*\)/DEVICE_ATTR_RW(${var})/;
7626				}
7627			} elsif ($show =~ /^${var}_show$/ &&
7628				 $store =~ /^NULL$/ &&
7629				 $octal_perms eq "0444") {
7630				if (WARN("DEVICE_ATTR_RO",
7631					 "Use DEVICE_ATTR_RO\n" . $herecurr) &&
7632				    $fix) {
7633					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*$show\s*,\s*NULL\s*\)/DEVICE_ATTR_RO(${var})/;
7634				}
7635			} elsif ($show =~ /^NULL$/ &&
7636				 $store =~ /^${var}_store$/ &&
7637				 $octal_perms eq "0200") {
7638				if (WARN("DEVICE_ATTR_WO",
7639					 "Use DEVICE_ATTR_WO\n" . $herecurr) &&
7640				    $fix) {
7641					$fixed[$fixlinenr] =~ s/\bDEVICE_ATTR\s*\(\s*$var\s*,\s*\Q$perms\E\s*,\s*NULL\s*,\s*$store\s*\)/DEVICE_ATTR_WO(${var})/;
7642				}
7643			} elsif ($octal_perms eq "0644" ||
7644				 $octal_perms eq "0444" ||
7645				 $octal_perms eq "0200") {
7646				my $newshow = "$show";
7647				$newshow = "${var}_show" if ($show ne "NULL" && $show ne "${var}_show");
7648				my $newstore = $store;
7649				$newstore = "${var}_store" if ($store ne "NULL" && $store ne "${var}_store");
7650				my $rename = "";
7651				if ($show ne $newshow) {
7652					$rename .= " '$show' to '$newshow'";
7653				}
7654				if ($store ne $newstore) {
7655					$rename .= " '$store' to '$newstore'";
7656				}
7657				WARN("DEVICE_ATTR_FUNCTIONS",
7658				     "Consider renaming function(s)$rename\n" . $herecurr);
7659			} else {
7660				WARN("DEVICE_ATTR_PERMS",
7661				     "DEVICE_ATTR unusual permissions '$perms' used\n" . $herecurr);
7662			}
7663		}
7664
7665# Mode permission misuses where it seems decimal should be octal
7666# This uses a shortcut match to avoid unnecessary uses of a slow foreach loop
7667# o Ignore module_param*(...) uses with a decimal 0 permission as that has a
7668#   specific definition of not visible in sysfs.
7669# o Ignore proc_create*(...) uses with a decimal 0 permission as that means
7670#   use the default permissions
7671		if ($perl_version_ok &&
7672		    defined $stat &&
7673		    $line =~ /$mode_perms_search/) {
7674			foreach my $entry (@mode_permission_funcs) {
7675				my $func = $entry->[0];
7676				my $arg_pos = $entry->[1];
7677
7678				my $lc = $stat =~ tr@\n@@;
7679				$lc = $lc + $linenr;
7680				my $stat_real = get_stat_real($linenr, $lc);
7681
7682				my $skip_args = "";
7683				if ($arg_pos > 1) {
7684					$arg_pos--;
7685					$skip_args = "(?:\\s*$FuncArg\\s*,\\s*){$arg_pos,$arg_pos}";
7686				}
7687				my $test = "\\b$func\\s*\\(${skip_args}($FuncArg(?:\\|\\s*$FuncArg)*)\\s*[,\\)]";
7688				if ($stat =~ /$test/) {
7689					my $val = $1;
7690					$val = $6 if ($skip_args ne "");
7691					if (!($func =~ /^(?:module_param|proc_create)/ && $val eq "0") &&
7692					    (($val =~ /^$Int$/ && $val !~ /^$Octal$/) ||
7693					     ($val =~ /^$Octal$/ && length($val) ne 4))) {
7694						ERROR("NON_OCTAL_PERMISSIONS",
7695						      "Use 4 digit octal (0777) not decimal permissions\n" . "$here\n" . $stat_real);
7696					}
7697					if ($val =~ /^$Octal$/ && (oct($val) & 02)) {
7698						ERROR("EXPORTED_WORLD_WRITABLE",
7699						      "Exporting writable files is usually an error. Consider more restrictive permissions.\n" . "$here\n" . $stat_real);
7700					}
7701				}
7702			}
7703		}
7704
7705# check for uses of S_<PERMS> that could be octal for readability
7706		while ($line =~ m{\b($multi_mode_perms_string_search)\b}g) {
7707			my $oval = $1;
7708			my $octal = perms_to_octal($oval);
7709			if (WARN("SYMBOLIC_PERMS",
7710				 "Symbolic permissions '$oval' are not preferred. Consider using octal permissions '$octal'.\n" . $herecurr) &&
7711			    $fix) {
7712				$fixed[$fixlinenr] =~ s/\Q$oval\E/$octal/;
7713			}
7714		}
7715
7716# validate content of MODULE_LICENSE against list from include/linux/module.h
7717		if ($line =~ /\bMODULE_LICENSE\s*\(\s*($String)\s*\)/) {
7718			my $extracted_string = get_quoted_string($line, $rawline);
7719			my $valid_licenses = qr{
7720						GPL|
7721						GPL\ v2|
7722						GPL\ and\ additional\ rights|
7723						Dual\ BSD/GPL|
7724						Dual\ MIT/GPL|
7725						Dual\ MPL/GPL|
7726						Proprietary
7727					}x;
7728			if ($extracted_string !~ /^"(?:$valid_licenses)"$/x) {
7729				WARN("MODULE_LICENSE",
7730				     "unknown module license " . $extracted_string . "\n" . $herecurr);
7731			}
7732			if (!$file && $extracted_string eq '"GPL v2"') {
7733				if (WARN("MODULE_LICENSE",
7734				     "Prefer \"GPL\" over \"GPL v2\" - see commit bf7fbeeae6db (\"module: Cure the MODULE_LICENSE \"GPL\" vs. \"GPL v2\" bogosity\")\n" . $herecurr) &&
7735				    $fix) {
7736					$fixed[$fixlinenr] =~ s/\bMODULE_LICENSE\s*\(\s*"GPL v2"\s*\)/MODULE_LICENSE("GPL")/;
7737				}
7738			}
7739		}
7740
7741# check for sysctl duplicate constants
7742		if ($line =~ /\.extra[12]\s*=\s*&(zero|one|int_max)\b/) {
7743			WARN("DUPLICATED_SYSCTL_CONST",
7744				"duplicated sysctl range checking value '$1', consider using the shared one in include/linux/sysctl.h\n" . $herecurr);
7745		}
7746
7747# Check that *_device_id tables have sentinel entries.
7748		if (defined $stat && $line =~ /struct\s+$dev_id_types\s+\w+\s*\[\s*\]\s*=\s*\{/) {
7749			my $stripped = $stat;
7750
7751			# Strip diff line prefixes.
7752			$stripped =~ s/(^|\n)./$1/g;
7753			# Line continuations.
7754			$stripped =~ s/\\\n/\n/g;
7755			# Strip whitespace, empty strings, zeroes, and commas.
7756			$stripped =~ s/""//g;
7757			$stripped =~ s/0x0//g;
7758			$stripped =~ s/[\s$;,0]//g;
7759			# Strip field assignments.
7760			$stripped =~ s/\.$Ident=//g;
7761
7762			if (!(substr($stripped, -4) eq "{}};" ||
7763			      substr($stripped, -6) eq "{{}}};" ||
7764			      $stripped =~ /ISAPNP_DEVICE_SINGLE_END}};$/ ||
7765			      $stripped =~ /ISAPNP_CARD_END}};$/ ||
7766			      $stripped =~ /NULL};$/ ||
7767			      $stripped =~ /PCMCIA_DEVICE_NULL};$/)) {
7768				ERROR("MISSING_SENTINEL", "missing sentinel in ID array\n" . "$here\n$stat\n");
7769			}
7770		}
7771
7772# check for uninitialized pointers with __free attribute
7773		while ($line =~ /\*\s*($Ident)\s+__free\s*\(\s*$Ident\s*\)\s*[,;]/g) {
7774			ERROR("UNINITIALIZED_PTR_WITH_FREE",
7775			      "pointer '$1' with __free attribute should be initialized\n" . $herecurr);
7776		}
7777	}
7778
7779	# If we have no input at all, then there is nothing to report on
7780	# so just keep quiet.
7781	if ($#rawlines == -1) {
7782		exit(0);
7783	}
7784
7785	# In mailback mode only produce a report in the negative, for
7786	# things that appear to be patches.
7787	if ($mailback && ($clean == 1 || !$is_patch)) {
7788		exit(0);
7789	}
7790
7791	# This is not a patch, and we are in 'no-patch' mode so
7792	# just keep quiet.
7793	if (!$chk_patch && !$is_patch) {
7794		exit(0);
7795	}
7796
7797	if (!$is_patch && $filename !~ /cover-letter\.patch$/) {
7798		ERROR("NOT_UNIFIED_DIFF",
7799		      "Does not appear to be a unified-diff format patch\n");
7800	}
7801	if ($is_patch && $has_commit_log && $chk_fixes_tag) {
7802		if ($needs_fixes_tag ne "" && !$is_revert && !$fixes_tag) {
7803			WARN("MISSING_FIXES_TAG",
7804				 "The commit message has '$needs_fixes_tag', perhaps it also needs a 'Fixes:' tag?\n");
7805		}
7806	}
7807	if ($is_patch && $has_commit_log && $chk_signoff) {
7808		if ($signoff == 0) {
7809			ERROR("MISSING_SIGN_OFF",
7810			      "Missing Signed-off-by: line(s)\n");
7811		} elsif ($authorsignoff != 1) {
7812			# authorsignoff values:
7813			# 0 -> missing sign off
7814			# 1 -> sign off identical
7815			# 2 -> names and addresses match, comments mismatch
7816			# 3 -> addresses match, names different
7817			# 4 -> names match, addresses different
7818			# 5 -> names match, addresses excluding subaddress details (refer RFC 5233) match
7819
7820			my $sob_msg = "'From: $author' != 'Signed-off-by: $author_sob'";
7821
7822			if ($authorsignoff == 0) {
7823				ERROR("NO_AUTHOR_SIGN_OFF",
7824				      "Missing Signed-off-by: line by nominal patch author '$author'\n");
7825			} elsif ($authorsignoff == 2) {
7826				CHK("FROM_SIGN_OFF_MISMATCH",
7827				    "From:/Signed-off-by: email comments mismatch: $sob_msg\n");
7828			} elsif ($authorsignoff == 3) {
7829				WARN("FROM_SIGN_OFF_MISMATCH",
7830				     "From:/Signed-off-by: email name mismatch: $sob_msg\n");
7831			} elsif ($authorsignoff == 4) {
7832				WARN("FROM_SIGN_OFF_MISMATCH",
7833				     "From:/Signed-off-by: email address mismatch: $sob_msg\n");
7834			} elsif ($authorsignoff == 5) {
7835				WARN("FROM_SIGN_OFF_MISMATCH",
7836				     "From:/Signed-off-by: email subaddress mismatch: $sob_msg\n");
7837			}
7838		}
7839	}
7840
7841	print report_dump();
7842	if ($summary && !($clean == 1 && $quiet == 1)) {
7843		print "$filename " if ($summary_file);
7844		print "total: $cnt_error errors, $cnt_warn warnings, " .
7845			(($check)? "$cnt_chk checks, " : "") .
7846			"$cnt_lines lines checked\n";
7847	}
7848
7849	if ($quiet == 0) {
7850		# If there were any defects found and not already fixing them
7851		if (!$clean and !$fix) {
7852			print << "EOM"
7853
7854NOTE: For some of the reported defects, checkpatch may be able to
7855      mechanically convert to the typical style using --fix or --fix-inplace.
7856EOM
7857		}
7858		# If there were whitespace errors which cleanpatch can fix
7859		# then suggest that.
7860		if ($rpt_cleaners) {
7861			$rpt_cleaners = 0;
7862			print << "EOM"
7863
7864NOTE: Whitespace errors detected.
7865      You may wish to use scripts/cleanpatch or scripts/cleanfile
7866EOM
7867		}
7868	}
7869
7870	if ($clean == 0 && $fix &&
7871	    ("@rawlines" ne "@fixed" ||
7872	     $#fixed_inserted >= 0 || $#fixed_deleted >= 0)) {
7873		my $newfile = $filename;
7874		$newfile .= ".EXPERIMENTAL-checkpatch-fixes" if (!$fix_inplace);
7875		my $linecount = 0;
7876		my $f;
7877
7878		@fixed = fix_inserted_deleted_lines(\@fixed, \@fixed_inserted, \@fixed_deleted);
7879
7880		open($f, '>', $newfile)
7881		    or die "$P: Can't open $newfile for write\n";
7882		foreach my $fixed_line (@fixed) {
7883			$linecount++;
7884			if ($file) {
7885				if ($linecount > 3) {
7886					$fixed_line =~ s/^\+//;
7887					print $f $fixed_line . "\n";
7888				}
7889			} else {
7890				print $f $fixed_line . "\n";
7891			}
7892		}
7893		close($f);
7894
7895		if (!$quiet) {
7896			print << "EOM";
7897
7898Wrote EXPERIMENTAL --fix correction(s) to '$newfile'
7899
7900Do _NOT_ trust the results written to this file.
7901Do _NOT_ submit these changes without inspecting them for correctness.
7902
7903This EXPERIMENTAL file is simply a convenience to help rewrite patches.
7904No warranties, expressed or implied...
7905EOM
7906		}
7907	}
7908
7909	if ($quiet == 0) {
7910		print "\n";
7911		if ($clean == 1) {
7912			print "$vname has no obvious style problems and is ready for submission.\n";
7913		} else {
7914			print "$vname has style problems, please review.\n";
7915		}
7916	}
7917	return $clean;
7918}
7919