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