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