Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Merge tag 'docs-for-linus' of git://git.lwn.net/linux

Pull documentation updates from Jonathan Corbet:
"Some big changes this month, headlined by the addition of a new
formatted documentation mechanism based on the Sphinx system.

The objectives here are to make it easier to create better-integrated
(and more attractive) documents while (eventually) dumping our
one-of-a-kind, cobbled-together system for something that is widely
used and maintained by others. There's a fair amount of information
what's being done, why, and how to use it in:

https://lwn.net/Articles/692704/
https://lwn.net/Articles/692705/

Closer to home, Documentation/kernel-documentation.rst describes how
it works.

For now, the new system exists alongside the old one; you should soon
see the GPU documentation converted over in the DRM pull and some
significant media conversion work as well. Once all the docs have
been moved over and we're convinced that the rough edges (of which are
are a few) have been smoothed over, the DocBook-based stuff should go
away.

Primary credit is to Jani Nikula for doing the heavy lifting to make
this stuff actually work; there has also been notable effort from
Markus Heiser, Daniel Vetter, and Mauro Carvalho Chehab.

Expect a couple of conflicts on the new index.rst file over the course
of the merge window; they are trivially resolvable. That file may be
a bit of a conflict magnet in the short term, but I don't expect that
situation to last for any real length of time.

Beyond that, of course, we have the usual collection of tweaks,
updates, and typo fixes"

* tag 'docs-for-linus' of git://git.lwn.net/linux: (77 commits)
doc-rst: kernel-doc: fix handling of address_space tags
Revert "doc/sphinx: Enable keep_warnings"
doc-rst: kernel-doc directive, fix state machine reporter
docs: deprecate kernel-doc-nano-HOWTO.txt
doc/sphinx: Enable keep_warnings
Documentation: add watermark_scale_factor to the list of vm systcl file
kernel-doc: Fix up warning output
docs: Get rid of some kernel-documentation warnings
doc-rst: add an option to ignore DocBooks when generating docs
workqueue: Fix a typo in workqueue.txt
Doc: ocfs: Fix typo in filesystems/ocfs2-online-filecheck.txt
Documentation/sphinx: skip build if user requested specific DOCBOOKS
Documentation: add cleanmediadocs to the documentation targets
Add .pyc files to .gitignore
Doc: PM: Fix a typo in intel_powerclamp.txt
doc-rst: flat-table directive - initial implementation
Documentation: add meta-documentation for Sphinx and kernel-doc
Documentation: tiny typo fix in usb/gadget_multi.txt
Documentation: fix wrong value in md.txt
bcache: documentation formatting, edited for clarity, stripe alignment notes
...

+2645 -422
+2
Documentation/.gitignore
··· 1 + output 2 + *.pyc
+2 -2
Documentation/00-INDEX
··· 255 255 - directory with info about the kernel build process. 256 256 kdump/ 257 257 - directory with mini HowTo on getting the crash dump code to work. 258 - kernel-doc-nano-HOWTO.txt 259 - - mini HowTo on generation and location of kernel documentation files. 260 258 kernel-docs.txt 261 259 - listing of various WWW + books that document kernel internals. 260 + kernel-documentation.rst 261 + - how to write and format reStructuredText kernel documentation 262 262 kernel-parameters.txt 263 263 - summary listing of command line / boot prompt args for the kernel. 264 264 kernel-per-CPU-kthreads.txt
+1 -1
Documentation/CodingStyle
··· 458 458 it. 459 459 460 460 When commenting the kernel API functions, please use the kernel-doc format. 461 - See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc 461 + See the files Documentation/kernel-documentation.rst and scripts/kernel-doc 462 462 for details. 463 463 464 464 Linux style for comments is the C89 "/* ... */" style.
+24 -6
Documentation/DocBook/Makefile
··· 6 6 # To add a new book the only step required is to add the book to the 7 7 # list of DOCBOOKS. 8 8 9 + ifeq ($(IGNORE_DOCBOOKS),) 10 + 9 11 DOCBOOKS := z8530book.xml device-drivers.xml \ 10 12 kernel-hacking.xml kernel-locking.xml deviceiobook.xml \ 11 13 writing_usb_driver.xml networking.xml \ ··· 35 33 PS_METHOD = $(prefer-db2x) 36 34 37 35 38 - ### 39 - # The targets that may be used. 40 - PHONY += xmldocs sgmldocs psdocs pdfdocs htmldocs mandocs installmandocs cleandocs 41 - 42 36 targets += $(DOCBOOKS) 43 37 BOOKS := $(addprefix $(obj)/,$(DOCBOOKS)) 44 38 xmldocs: $(BOOKS) ··· 60 62 find $(obj)/man -name '*.9.gz' -printf '%h %f\n' | \ 61 63 sort -k 2 -k 1 | uniq -f 1 | sed -e 's: :/:' | \ 62 64 xargs install -m 644 -t /usr/local/man/man9/ 65 + 66 + # no-op for the DocBook toolchain 67 + epubdocs: 63 68 64 69 ### 65 70 #External programs used ··· 217 216 -e "s/>/\\&gt;/g"; \ 218 217 echo "</programlisting>") > $@ 219 218 219 + else 220 + 221 + # Needed, due to cleanmediadocs 222 + include Documentation/DocBook/media/Makefile 223 + 224 + htmldocs: 225 + pdfdocs: 226 + psdocs: 227 + xmldocs: 228 + installmandocs: 229 + 230 + endif # IGNORE_DOCBOOKS 231 + 232 + 220 233 ### 221 234 # Help targets as used by the top-level makefile 222 235 dochelp: 223 - @echo ' Linux kernel internal documentation in different formats:' 236 + @echo ' Linux kernel internal documentation in different formats (DocBook):' 224 237 @echo ' htmldocs - HTML' 225 238 @echo ' pdfdocs - PDF' 226 239 @echo ' psdocs - Postscript' ··· 243 228 @echo ' installmandocs - install man pages generated by mandocs' 244 229 @echo ' cleandocs - clean all generated DocBook files' 245 230 @echo 246 - @echo 'make DOCBOOKS="s1.xml s2.xml" [target] Generate only docs s1.xml s2.xml' 231 + @echo ' make DOCBOOKS="s1.xml s2.xml" [target] Generate only docs s1.xml s2.xml' 247 232 @echo ' valid values for DOCBOOKS are: $(DOCBOOKS)' 233 + @echo 234 + @echo " make IGNORE_DOCBOOKS=1 [target] Don't generate docs from Docbook" 235 + @echo ' This is useful to generate only the ReST docs (Sphinx)' 248 236 249 237 250 238 ###
+78
Documentation/Makefile.sphinx
··· 1 + # -*- makefile -*- 2 + # Makefile for Sphinx documentation 3 + # 4 + 5 + # You can set these variables from the command line. 6 + SPHINXBUILD = sphinx-build 7 + SPHINXOPTS = 8 + PAPER = 9 + BUILDDIR = $(obj)/output 10 + 11 + # User-friendly check for sphinx-build 12 + HAVE_SPHINX := $(shell if which $(SPHINXBUILD) >/dev/null 2>&1; then echo 1; else echo 0; fi) 13 + 14 + ifeq ($(HAVE_SPHINX),0) 15 + 16 + .DEFAULT: 17 + $(warning The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed and in PATH, or set the SPHINXBUILD make variable to point to the full path of the '$(SPHINXBUILD)' executable.) 18 + @echo " SKIP Sphinx $@ target." 19 + 20 + else ifneq ($(DOCBOOKS),) 21 + 22 + # Skip Sphinx build if the user explicitly requested DOCBOOKS. 23 + .DEFAULT: 24 + @echo " SKIP Sphinx $@ target (DOCBOOKS specified)." 25 + 26 + else # HAVE_SPHINX 27 + 28 + # User-friendly check for rst2pdf 29 + HAVE_RST2PDF := $(shell if python -c "import rst2pdf" >/dev/null 2>&1; then echo 1; else echo 0; fi) 30 + 31 + # Internal variables. 32 + PAPEROPT_a4 = -D latex_paper_size=a4 33 + PAPEROPT_letter = -D latex_paper_size=letter 34 + KERNELDOC = $(srctree)/scripts/kernel-doc 35 + KERNELDOC_CONF = -D kerneldoc_srctree=$(srctree) -D kerneldoc_bin=$(KERNELDOC) 36 + ALLSPHINXOPTS = -D version=$(KERNELVERSION) -D release=$(KERNELRELEASE) -d $(BUILDDIR)/.doctrees $(KERNELDOC_CONF) $(PAPEROPT_$(PAPER)) -c $(srctree)/$(src) $(SPHINXOPTS) $(srctree)/$(src) 37 + # the i18n builder cannot share the environment and doctrees with the others 38 + I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 39 + 40 + quiet_cmd_sphinx = SPHINX $@ 41 + cmd_sphinx = $(SPHINXBUILD) -b $2 $(ALLSPHINXOPTS) $(BUILDDIR)/$2 42 + 43 + htmldocs: 44 + $(call cmd,sphinx,html) 45 + 46 + pdfdocs: 47 + ifeq ($(HAVE_RST2PDF),0) 48 + $(warning The Python 'rst2pdf' module was not found. Make sure you have the module installed to produce PDF output.) 49 + @echo " SKIP Sphinx $@ target." 50 + else # HAVE_RST2PDF 51 + $(call cmd,sphinx,pdf) 52 + endif # HAVE_RST2PDF 53 + 54 + epubdocs: 55 + $(call cmd,sphinx,epub) 56 + 57 + xmldocs: 58 + $(call cmd,sphinx,xml) 59 + 60 + # no-ops for the Sphinx toolchain 61 + sgmldocs: 62 + psdocs: 63 + mandocs: 64 + installmandocs: 65 + cleanmediadocs: 66 + 67 + cleandocs: 68 + $(Q)rm -rf $(BUILDDIR) 69 + 70 + dochelp: 71 + @echo ' Linux kernel internal documentation in different formats (Sphinx):' 72 + @echo ' htmldocs - HTML' 73 + @echo ' pdfdocs - PDF' 74 + @echo ' epubdocs - EPUB' 75 + @echo ' xmldocs - XML' 76 + @echo ' cleandocs - clean all generated files' 77 + 78 + endif # HAVE_SPHINX
+187 -10
Documentation/bcache.txt
··· 1 - Say you've got a big slow raid 6, and an X-25E or three. Wouldn't it be 1 + Say you've got a big slow raid 6, and an ssd or three. Wouldn't it be 2 2 nice if you could use them as cache... Hence bcache. 3 3 4 4 Wiki and git repositories are at: ··· 8 8 9 9 It's designed around the performance characteristics of SSDs - it only allocates 10 10 in erase block sized buckets, and it uses a hybrid btree/log to track cached 11 - extants (which can be anywhere from a single sector to the bucket size). It's 11 + extents (which can be anywhere from a single sector to the bucket size). It's 12 12 designed to avoid random writes at all costs; it fills up an erase block 13 13 sequentially, then issues a discard before reusing it. 14 14 ··· 55 55 Registering the backing device makes the bcache device show up in /dev; you can 56 56 now format it and use it as normal. But the first time using a new bcache 57 57 device, it'll be running in passthrough mode until you attach it to a cache. 58 - See the section on attaching. 58 + If you are thinking about using bcache later, it is recommended to setup all your 59 + slow devices as bcache backing devices without a cache, and you can choose to add 60 + a caching device later. 61 + See 'ATTACHING' section below. 59 62 60 63 The devices show up as: 61 64 ··· 75 72 mount /dev/bcache0 /mnt 76 73 77 74 You can control bcache devices through sysfs at /sys/block/bcache<N>/bcache . 75 + You can also control them through /sys/fs//bcache/<cset-uuid>/ . 78 76 79 77 Cache devices are managed as sets; multiple caches per set isn't supported yet 80 78 but will allow for mirroring of metadata and dirty data in the future. Your new 81 79 cache set shows up as /sys/fs/bcache/<UUID> 82 80 83 - ATTACHING: 81 + ATTACHING 82 + --------- 84 83 85 84 After your cache device and backing device are registered, the backing device 86 85 must be attached to your cache set to enable caching. Attaching a backing ··· 110 105 cache, don't expect the filesystem to be recoverable - you will have massive 111 106 filesystem corruption, though ext4's fsck does work miracles. 112 107 113 - ERROR HANDLING: 108 + ERROR HANDLING 109 + -------------- 114 110 115 111 Bcache tries to transparently handle IO errors to/from the cache device without 116 112 affecting normal operation; if it sees too many errors (the threshold is ··· 133 127 writeback mode). It currently doesn't do anything intelligent if it fails to 134 128 read some of the dirty data, though. 135 129 136 - TROUBLESHOOTING PERFORMANCE: 130 + 131 + HOWTO/COOKBOOK 132 + -------------- 133 + 134 + A) Starting a bcache with a missing caching device 135 + 136 + If registering the backing device doesn't help, it's already there, you just need 137 + to force it to run without the cache: 138 + host:~# echo /dev/sdb1 > /sys/fs/bcache/register 139 + [ 119.844831] bcache: register_bcache() error opening /dev/sdb1: device already registered 140 + 141 + Next, you try to register your caching device if it's present. However 142 + if it's absent, or registration fails for some reason, you can still 143 + start your bcache without its cache, like so: 144 + host:/sys/block/sdb/sdb1/bcache# echo 1 > running 145 + 146 + Note that this may cause data loss if you were running in writeback mode. 147 + 148 + 149 + B) Bcache does not find its cache 150 + 151 + host:/sys/block/md5/bcache# echo 0226553a-37cf-41d5-b3ce-8b1e944543a8 > attach 152 + [ 1933.455082] bcache: bch_cached_dev_attach() Couldn't find uuid for md5 in set 153 + [ 1933.478179] bcache: __cached_dev_store() Can't attach 0226553a-37cf-41d5-b3ce-8b1e944543a8 154 + [ 1933.478179] : cache set not found 155 + 156 + In this case, the caching device was simply not registered at boot 157 + or disappeared and came back, and needs to be (re-)registered: 158 + host:/sys/block/md5/bcache# echo /dev/sdh2 > /sys/fs/bcache/register 159 + 160 + 161 + C) Corrupt bcache crashes the kernel at device registration time: 162 + 163 + This should never happen. If it does happen, then you have found a bug! 164 + Please report it to the bcache development list: linux-bcache@vger.kernel.org 165 + 166 + Be sure to provide as much information that you can including kernel dmesg 167 + output if available so that we may assist. 168 + 169 + 170 + D) Recovering data without bcache: 171 + 172 + If bcache is not available in the kernel, a filesystem on the backing 173 + device is still available at an 8KiB offset. So either via a loopdev 174 + of the backing device created with --offset 8K, or any value defined by 175 + --data-offset when you originally formatted bcache with `make-bcache`. 176 + 177 + For example: 178 + losetup -o 8192 /dev/loop0 /dev/your_bcache_backing_dev 179 + 180 + This should present your unmodified backing device data in /dev/loop0 181 + 182 + If your cache is in writethrough mode, then you can safely discard the 183 + cache device without loosing data. 184 + 185 + 186 + E) Wiping a cache device 187 + 188 + host:~# wipefs -a /dev/sdh2 189 + 16 bytes were erased at offset 0x1018 (bcache) 190 + they were: c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81 191 + 192 + After you boot back with bcache enabled, you recreate the cache and attach it: 193 + host:~# make-bcache -C /dev/sdh2 194 + UUID: 7be7e175-8f4c-4f99-94b2-9c904d227045 195 + Set UUID: 5bc072a8-ab17-446d-9744-e247949913c1 196 + version: 0 197 + nbuckets: 106874 198 + block_size: 1 199 + bucket_size: 1024 200 + nr_in_set: 1 201 + nr_this_dev: 0 202 + first_bucket: 1 203 + [ 650.511912] bcache: run_cache_set() invalidating existing data 204 + [ 650.549228] bcache: register_cache() registered cache device sdh2 205 + 206 + start backing device with missing cache: 207 + host:/sys/block/md5/bcache# echo 1 > running 208 + 209 + attach new cache: 210 + host:/sys/block/md5/bcache# echo 5bc072a8-ab17-446d-9744-e247949913c1 > attach 211 + [ 865.276616] bcache: bch_cached_dev_attach() Caching md5 as bcache0 on set 5bc072a8-ab17-446d-9744-e247949913c1 212 + 213 + 214 + F) Remove or replace a caching device 215 + 216 + host:/sys/block/sda/sda7/bcache# echo 1 > detach 217 + [ 695.872542] bcache: cached_dev_detach_finish() Caching disabled for sda7 218 + 219 + host:~# wipefs -a /dev/nvme0n1p4 220 + wipefs: error: /dev/nvme0n1p4: probing initialization failed: Device or resource busy 221 + Ooops, it's disabled, but not unregistered, so it's still protected 222 + 223 + We need to go and unregister it: 224 + host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# ls -l cache0 225 + lrwxrwxrwx 1 root root 0 Feb 25 18:33 cache0 -> ../../../devices/pci0000:00/0000:00:1d.0/0000:70:00.0/nvme/nvme0/nvme0n1/nvme0n1p4/bcache/ 226 + host:/sys/fs/bcache/b7ba27a1-2398-4649-8ae3-0959f57ba128# echo 1 > stop 227 + kernel: [ 917.041908] bcache: cache_set_free() Cache set b7ba27a1-2398-4649-8ae3-0959f57ba128 unregistered 228 + 229 + Now we can wipe it: 230 + host:~# wipefs -a /dev/nvme0n1p4 231 + /dev/nvme0n1p4: 16 bytes were erased at offset 0x00001018 (bcache): c6 85 73 f6 4e 1a 45 ca 82 65 f5 7f 48 ba 6d 81 232 + 233 + 234 + G) dm-crypt and bcache 235 + 236 + First setup bcache unencrypted and then install dmcrypt on top of 237 + /dev/bcache<N> This will work faster than if you dmcrypt both the backing 238 + and caching devices and then install bcache on top. [benchmarks?] 239 + 240 + 241 + H) Stop/free a registered bcache to wipe and/or recreate it 242 + 243 + Suppose that you need to free up all bcache references so that you can 244 + fdisk run and re-register a changed partition table, which won't work 245 + if there are any active backing or caching devices left on it: 246 + 247 + 1) Is it present in /dev/bcache* ? (there are times where it won't be) 248 + 249 + If so, it's easy: 250 + host:/sys/block/bcache0/bcache# echo 1 > stop 251 + 252 + 2) But if your backing device is gone, this won't work: 253 + host:/sys/block/bcache0# cd bcache 254 + bash: cd: bcache: No such file or directory 255 + 256 + In this case, you may have to unregister the dmcrypt block device that 257 + references this bcache to free it up: 258 + host:~# dmsetup remove oldds1 259 + bcache: bcache_device_free() bcache0 stopped 260 + bcache: cache_set_free() Cache set 5bc072a8-ab17-446d-9744-e247949913c1 unregistered 261 + 262 + This causes the backing bcache to be removed from /sys/fs/bcache and 263 + then it can be reused. This would be true of any block device stacking 264 + where bcache is a lower device. 265 + 266 + 3) In other cases, you can also look in /sys/fs/bcache/: 267 + 268 + host:/sys/fs/bcache# ls -l */{cache?,bdev?} 269 + lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/bdev1 -> ../../../devices/virtual/block/dm-1/bcache/ 270 + lrwxrwxrwx 1 root root 0 Mar 5 09:39 0226553a-37cf-41d5-b3ce-8b1e944543a8/cache0 -> ../../../devices/virtual/block/dm-4/bcache/ 271 + lrwxrwxrwx 1 root root 0 Mar 5 09:39 5bc072a8-ab17-446d-9744-e247949913c1/cache0 -> ../../../devices/pci0000:00/0000:00:01.0/0000:01:00.0/ata10/host9/target9:0:0/9:0:0:0/block/sdl/sdl2/bcache/ 272 + 273 + The device names will show which UUID is relevant, cd in that directory 274 + and stop the cache: 275 + host:/sys/fs/bcache/5bc072a8-ab17-446d-9744-e247949913c1# echo 1 > stop 276 + 277 + This will free up bcache references and let you reuse the partition for 278 + other purposes. 279 + 280 + 281 + 282 + TROUBLESHOOTING PERFORMANCE 283 + --------------------------- 137 284 138 285 Bcache has a bunch of config options and tunables. The defaults are intended to 139 286 be reasonable for typical desktop and server workloads, but they're not what you 140 287 want for getting the best possible numbers when benchmarking. 288 + 289 + - Backing device alignment 290 + 291 + The default metadata size in bcache is 8k. If your backing device is 292 + RAID based, then be sure to align this by a multiple of your stride 293 + width using `make-bcache --data-offset`. If you intend to expand your 294 + disk array in the future, then multiply a series of primes by your 295 + raid stripe size to get the disk multiples that you would like. 296 + 297 + For example: If you have a 64k stripe size, then the following offset 298 + would provide alignment for many common RAID5 data spindle counts: 299 + 64k * 2*2*2*3*3*5*7 bytes = 161280k 300 + 301 + That space is wasted, but for only 157.5MB you can grow your RAID 5 302 + volume to the following data-spindle counts without re-aligning: 303 + 3,4,5,6,7,8,9,10,12,14,15,18,20,21 ... 141 304 142 305 - Bad write performance 143 306 ··· 315 140 maturity, but simply because in writeback mode you'll lose data if something 316 141 happens to your SSD) 317 142 318 - # echo writeback > /sys/block/bcache0/cache_mode 143 + # echo writeback > /sys/block/bcache0/bcache/cache_mode 319 144 320 145 - Bad performance, or traffic not going to the SSD that you'd expect 321 146 ··· 368 193 Solution: warm the cache by doing writes, or use the testing branch (there's 369 194 a fix for the issue there). 370 195 371 - SYSFS - BACKING DEVICE: 196 + 197 + SYSFS - BACKING DEVICE 198 + ---------------------- 372 199 373 200 Available at /sys/block/<bdev>/bcache, /sys/block/bcache*/bcache and 374 201 (if attached) /sys/fs/bcache/<cset-uuid>/bdev* ··· 415 238 against all new requests to determine which new requests are sequential 416 239 continuations of previous requests for the purpose of determining sequential 417 240 cutoff. This is necessary if the sequential cutoff value is greater than the 418 - maximum acceptable sequential size for any single request. 241 + maximum acceptable sequential size for any single request. 419 242 420 243 state 421 244 The backing device can be in one of four different states: ··· 502 325 Size of buckets 503 326 504 327 cache<0..n> 505 - Symlink to each of the cache devices comprising this cache set. 328 + Symlink to each of the cache devices comprising this cache set. 506 329 507 330 cache_available_percent 508 331 Percentage of cache device which doesn't contain dirty data, and could
+414
Documentation/conf.py
··· 1 + # -*- coding: utf-8 -*- 2 + # 3 + # The Linux Kernel documentation build configuration file, created by 4 + # sphinx-quickstart on Fri Feb 12 13:51:46 2016. 5 + # 6 + # This file is execfile()d with the current directory set to its 7 + # containing dir. 8 + # 9 + # Note that not all possible configuration values are present in this 10 + # autogenerated file. 11 + # 12 + # All configuration values have a default; values that are commented out 13 + # serve to show the default. 14 + 15 + import sys 16 + import os 17 + 18 + # If extensions (or modules to document with autodoc) are in another directory, 19 + # add these directories to sys.path here. If the directory is relative to the 20 + # documentation root, use os.path.abspath to make it absolute, like shown here. 21 + sys.path.insert(0, os.path.abspath('sphinx')) 22 + 23 + # -- General configuration ------------------------------------------------ 24 + 25 + # If your documentation needs a minimal Sphinx version, state it here. 26 + #needs_sphinx = '1.0' 27 + 28 + # Add any Sphinx extension module names here, as strings. They can be 29 + # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 + # ones. 31 + extensions = ['kernel-doc', 'rstFlatTable'] 32 + 33 + # Gracefully handle missing rst2pdf. 34 + try: 35 + import rst2pdf 36 + extensions += ['rst2pdf.pdfbuilder'] 37 + except ImportError: 38 + pass 39 + 40 + # Add any paths that contain templates here, relative to this directory. 41 + templates_path = ['_templates'] 42 + 43 + # The suffix(es) of source filenames. 44 + # You can specify multiple suffix as a list of string: 45 + # source_suffix = ['.rst', '.md'] 46 + source_suffix = '.rst' 47 + 48 + # The encoding of source files. 49 + #source_encoding = 'utf-8-sig' 50 + 51 + # The master toctree document. 52 + master_doc = 'index' 53 + 54 + # General information about the project. 55 + project = 'The Linux Kernel' 56 + copyright = '2016, The kernel development community' 57 + author = 'The kernel development community' 58 + 59 + # The version info for the project you're documenting, acts as replacement for 60 + # |version| and |release|, also used in various other places throughout the 61 + # built documents. 62 + # 63 + # In a normal build, version and release are are set to KERNELVERSION and 64 + # KERNELRELEASE, respectively, from the Makefile via Sphinx command line 65 + # arguments. 66 + # 67 + # The following code tries to extract the information by reading the Makefile, 68 + # when Sphinx is run directly (e.g. by Read the Docs). 69 + try: 70 + makefile_version = None 71 + makefile_patchlevel = None 72 + for line in open('../Makefile'): 73 + key, val = [x.strip() for x in line.split('=', 2)] 74 + if key == 'VERSION': 75 + makefile_version = val 76 + elif key == 'PATCHLEVEL': 77 + makefile_patchlevel = val 78 + if makefile_version and makefile_patchlevel: 79 + break 80 + except: 81 + pass 82 + finally: 83 + if makefile_version and makefile_patchlevel: 84 + version = release = makefile_version + '.' + makefile_patchlevel 85 + else: 86 + sys.stderr.write('Warning: Could not extract kernel version\n') 87 + version = release = "unknown version" 88 + 89 + # The language for content autogenerated by Sphinx. Refer to documentation 90 + # for a list of supported languages. 91 + # 92 + # This is also used if you do content translation via gettext catalogs. 93 + # Usually you set "language" from the command line for these cases. 94 + language = None 95 + 96 + # There are two options for replacing |today|: either, you set today to some 97 + # non-false value, then it is used: 98 + #today = '' 99 + # Else, today_fmt is used as the format for a strftime call. 100 + #today_fmt = '%B %d, %Y' 101 + 102 + # List of patterns, relative to source directory, that match files and 103 + # directories to ignore when looking for source files. 104 + exclude_patterns = ['output'] 105 + 106 + # The reST default role (used for this markup: `text`) to use for all 107 + # documents. 108 + #default_role = None 109 + 110 + # If true, '()' will be appended to :func: etc. cross-reference text. 111 + #add_function_parentheses = True 112 + 113 + # If true, the current module name will be prepended to all description 114 + # unit titles (such as .. function::). 115 + #add_module_names = True 116 + 117 + # If true, sectionauthor and moduleauthor directives will be shown in the 118 + # output. They are ignored by default. 119 + #show_authors = False 120 + 121 + # The name of the Pygments (syntax highlighting) style to use. 122 + pygments_style = 'sphinx' 123 + 124 + # A list of ignored prefixes for module index sorting. 125 + #modindex_common_prefix = [] 126 + 127 + # If true, keep warnings as "system message" paragraphs in the built documents. 128 + #keep_warnings = False 129 + 130 + # If true, `todo` and `todoList` produce output, else they produce nothing. 131 + todo_include_todos = False 132 + 133 + primary_domain = 'C' 134 + highlight_language = 'C' 135 + 136 + # -- Options for HTML output ---------------------------------------------- 137 + 138 + # The theme to use for HTML and HTML Help pages. See the documentation for 139 + # a list of builtin themes. 140 + 141 + # The Read the Docs theme is available from 142 + # - https://github.com/snide/sphinx_rtd_theme 143 + # - https://pypi.python.org/pypi/sphinx_rtd_theme 144 + # - python-sphinx-rtd-theme package (on Debian) 145 + try: 146 + import sphinx_rtd_theme 147 + html_theme = 'sphinx_rtd_theme' 148 + html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 149 + except ImportError: 150 + sys.stderr.write('Warning: The Sphinx \'sphinx_rtd_theme\' HTML theme was not found. Make sure you have the theme installed to produce pretty HTML output. Falling back to the default theme.\n') 151 + 152 + # Theme options are theme-specific and customize the look and feel of a theme 153 + # further. For a list of options available for each theme, see the 154 + # documentation. 155 + #html_theme_options = {} 156 + 157 + # Add any paths that contain custom themes here, relative to this directory. 158 + #html_theme_path = [] 159 + 160 + # The name for this set of Sphinx documents. If None, it defaults to 161 + # "<project> v<release> documentation". 162 + #html_title = None 163 + 164 + # A shorter title for the navigation bar. Default is the same as html_title. 165 + #html_short_title = None 166 + 167 + # The name of an image file (relative to this directory) to place at the top 168 + # of the sidebar. 169 + #html_logo = None 170 + 171 + # The name of an image file (within the static path) to use as favicon of the 172 + # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 173 + # pixels large. 174 + #html_favicon = None 175 + 176 + # Add any paths that contain custom static files (such as style sheets) here, 177 + # relative to this directory. They are copied after the builtin static files, 178 + # so a file named "default.css" will overwrite the builtin "default.css". 179 + #html_static_path = ['_static'] 180 + 181 + # Add any extra paths that contain custom files (such as robots.txt or 182 + # .htaccess) here, relative to this directory. These files are copied 183 + # directly to the root of the documentation. 184 + #html_extra_path = [] 185 + 186 + # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 187 + # using the given strftime format. 188 + #html_last_updated_fmt = '%b %d, %Y' 189 + 190 + # If true, SmartyPants will be used to convert quotes and dashes to 191 + # typographically correct entities. 192 + #html_use_smartypants = True 193 + 194 + # Custom sidebar templates, maps document names to template names. 195 + #html_sidebars = {} 196 + 197 + # Additional templates that should be rendered to pages, maps page names to 198 + # template names. 199 + #html_additional_pages = {} 200 + 201 + # If false, no module index is generated. 202 + #html_domain_indices = True 203 + 204 + # If false, no index is generated. 205 + #html_use_index = True 206 + 207 + # If true, the index is split into individual pages for each letter. 208 + #html_split_index = False 209 + 210 + # If true, links to the reST sources are added to the pages. 211 + #html_show_sourcelink = True 212 + 213 + # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 214 + #html_show_sphinx = True 215 + 216 + # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 217 + #html_show_copyright = True 218 + 219 + # If true, an OpenSearch description file will be output, and all pages will 220 + # contain a <link> tag referring to it. The value of this option must be the 221 + # base URL from which the finished HTML is served. 222 + #html_use_opensearch = '' 223 + 224 + # This is the file name suffix for HTML files (e.g. ".xhtml"). 225 + #html_file_suffix = None 226 + 227 + # Language to be used for generating the HTML full-text search index. 228 + # Sphinx supports the following languages: 229 + # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 230 + # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' 231 + #html_search_language = 'en' 232 + 233 + # A dictionary with options for the search language support, empty by default. 234 + # Now only 'ja' uses this config value 235 + #html_search_options = {'type': 'default'} 236 + 237 + # The name of a javascript file (relative to the configuration directory) that 238 + # implements a search results scorer. If empty, the default will be used. 239 + #html_search_scorer = 'scorer.js' 240 + 241 + # Output file base name for HTML help builder. 242 + htmlhelp_basename = 'TheLinuxKerneldoc' 243 + 244 + # -- Options for LaTeX output --------------------------------------------- 245 + 246 + latex_elements = { 247 + # The paper size ('letterpaper' or 'a4paper'). 248 + #'papersize': 'letterpaper', 249 + 250 + # The font size ('10pt', '11pt' or '12pt'). 251 + #'pointsize': '10pt', 252 + 253 + # Additional stuff for the LaTeX preamble. 254 + #'preamble': '', 255 + 256 + # Latex figure (float) alignment 257 + #'figure_align': 'htbp', 258 + } 259 + 260 + # Grouping the document tree into LaTeX files. List of tuples 261 + # (source start file, target name, title, 262 + # author, documentclass [howto, manual, or own class]). 263 + latex_documents = [ 264 + (master_doc, 'TheLinuxKernel.tex', 'The Linux Kernel Documentation', 265 + 'The kernel development community', 'manual'), 266 + ] 267 + 268 + # The name of an image file (relative to this directory) to place at the top of 269 + # the title page. 270 + #latex_logo = None 271 + 272 + # For "manual" documents, if this is true, then toplevel headings are parts, 273 + # not chapters. 274 + #latex_use_parts = False 275 + 276 + # If true, show page references after internal links. 277 + #latex_show_pagerefs = False 278 + 279 + # If true, show URL addresses after external links. 280 + #latex_show_urls = False 281 + 282 + # Documents to append as an appendix to all manuals. 283 + #latex_appendices = [] 284 + 285 + # If false, no module index is generated. 286 + #latex_domain_indices = True 287 + 288 + 289 + # -- Options for manual page output --------------------------------------- 290 + 291 + # One entry per manual page. List of tuples 292 + # (source start file, name, description, authors, manual section). 293 + man_pages = [ 294 + (master_doc, 'thelinuxkernel', 'The Linux Kernel Documentation', 295 + [author], 1) 296 + ] 297 + 298 + # If true, show URL addresses after external links. 299 + #man_show_urls = False 300 + 301 + 302 + # -- Options for Texinfo output ------------------------------------------- 303 + 304 + # Grouping the document tree into Texinfo files. List of tuples 305 + # (source start file, target name, title, author, 306 + # dir menu entry, description, category) 307 + texinfo_documents = [ 308 + (master_doc, 'TheLinuxKernel', 'The Linux Kernel Documentation', 309 + author, 'TheLinuxKernel', 'One line description of project.', 310 + 'Miscellaneous'), 311 + ] 312 + 313 + # Documents to append as an appendix to all manuals. 314 + #texinfo_appendices = [] 315 + 316 + # If false, no module index is generated. 317 + #texinfo_domain_indices = True 318 + 319 + # How to display URL addresses: 'footnote', 'no', or 'inline'. 320 + #texinfo_show_urls = 'footnote' 321 + 322 + # If true, do not generate a @detailmenu in the "Top" node's menu. 323 + #texinfo_no_detailmenu = False 324 + 325 + 326 + # -- Options for Epub output ---------------------------------------------- 327 + 328 + # Bibliographic Dublin Core info. 329 + epub_title = project 330 + epub_author = author 331 + epub_publisher = author 332 + epub_copyright = copyright 333 + 334 + # The basename for the epub file. It defaults to the project name. 335 + #epub_basename = project 336 + 337 + # The HTML theme for the epub output. Since the default themes are not 338 + # optimized for small screen space, using the same theme for HTML and epub 339 + # output is usually not wise. This defaults to 'epub', a theme designed to save 340 + # visual space. 341 + #epub_theme = 'epub' 342 + 343 + # The language of the text. It defaults to the language option 344 + # or 'en' if the language is not set. 345 + #epub_language = '' 346 + 347 + # The scheme of the identifier. Typical schemes are ISBN or URL. 348 + #epub_scheme = '' 349 + 350 + # The unique identifier of the text. This can be a ISBN number 351 + # or the project homepage. 352 + #epub_identifier = '' 353 + 354 + # A unique identification for the text. 355 + #epub_uid = '' 356 + 357 + # A tuple containing the cover image and cover page html template filenames. 358 + #epub_cover = () 359 + 360 + # A sequence of (type, uri, title) tuples for the guide element of content.opf. 361 + #epub_guide = () 362 + 363 + # HTML files that should be inserted before the pages created by sphinx. 364 + # The format is a list of tuples containing the path and title. 365 + #epub_pre_files = [] 366 + 367 + # HTML files that should be inserted after the pages created by sphinx. 368 + # The format is a list of tuples containing the path and title. 369 + #epub_post_files = [] 370 + 371 + # A list of files that should not be packed into the epub file. 372 + epub_exclude_files = ['search.html'] 373 + 374 + # The depth of the table of contents in toc.ncx. 375 + #epub_tocdepth = 3 376 + 377 + # Allow duplicate toc entries. 378 + #epub_tocdup = True 379 + 380 + # Choose between 'default' and 'includehidden'. 381 + #epub_tocscope = 'default' 382 + 383 + # Fix unsupported image types using the Pillow. 384 + #epub_fix_images = False 385 + 386 + # Scale large images. 387 + #epub_max_image_width = 0 388 + 389 + # How to display URL addresses: 'footnote', 'no', or 'inline'. 390 + #epub_show_urls = 'inline' 391 + 392 + # If false, no index is generated. 393 + #epub_use_index = True 394 + 395 + #======= 396 + # rst2pdf 397 + # 398 + # Grouping the document tree into PDF files. List of tuples 399 + # (source start file, target name, title, author, options). 400 + # 401 + # See the Sphinx chapter of http://ralsina.me/static/manual.pdf 402 + # 403 + # FIXME: Do not add the index file here; the result will be too big. Adding 404 + # multiple PDF files here actually tries to get the cross-referencing right 405 + # *between* PDF files. 406 + pdf_documents = [ 407 + ('index', u'Kernel', u'Kernel', u'J. Random Bozo'), 408 + ] 409 + 410 + # kernel-doc extension configuration for running Sphinx directly (e.g. by Read 411 + # the Docs). In a normal build, these are supplied from the Makefile via command 412 + # line arguments. 413 + kerneldoc_bin = '../scripts/kernel-doc' 414 + kerneldoc_srctree = '..'
+1 -1
Documentation/development-process/4.Coding
··· 346 346 comments for the future; indeed, this can be a useful activity for 347 347 beginning kernel developers. The format of these comments, along with some 348 348 information on how to create kerneldoc templates can be found in the file 349 - Documentation/kernel-doc-nano-HOWTO.txt. 349 + Documentation/kernel-documentation.rst. 350 350 351 351 Anybody who reads through a significant amount of existing kernel code will 352 352 note that, often, comments are most notable by their absence. Once again,
+1 -1
Documentation/dmaengine/provider.txt
··· 323 323 * device_resume 324 324 - Resumes a transfer on the channel 325 325 - This command should operate synchronously on the channel, 326 - pausing right away the work of the given channel 326 + resuming right away the work of the given channel 327 327 328 328 * device_terminate_all 329 329 - Aborts all the pending and ongoing transfers on the channel
+5 -5
Documentation/filesystems/ocfs2-online-filecheck.txt
··· 5 5 6 6 Introduction 7 7 ============ 8 - OCFS2 is often used in high-availaibility systems. However, OCFS2 usually 8 + OCFS2 is often used in high-availability systems. However, OCFS2 usually 9 9 converts the filesystem to read-only when encounters an error. This may not be 10 10 necessary, since turning the filesystem read-only would affect other running 11 11 processes as well, decreasing availability. 12 12 Then, a mount option (errors=continue) is introduced, which would return the 13 - -EIO errno to the calling process and terminate furhter processing so that the 13 + -EIO errno to the calling process and terminate further processing so that the 14 14 filesystem is not corrupted further. The filesystem is not converted to 15 15 read-only, and the problematic file's inode number is reported in the kernel 16 16 log. The user can try to check/fix this file via online filecheck feature. ··· 44 44 45 45 /sys/fs/ocfs2/<devname>/filecheck 46 46 47 - Here, <devname> indicates the name of OCFS2 volumn device which has been already 47 + Here, <devname> indicates the name of OCFS2 volume device which has been already 48 48 mounted. The file above would accept inode numbers. This could be used to 49 49 communicate with kernel space, tell which file(inode number) will be checked or 50 50 fixed. Currently, three operations are supported, which includes checking ··· 76 76 This time, the <ERROR> column indicates whether this fix is successful or not. 77 77 78 78 3. The record cache is used to store the history of check/fix results. It's 79 - defalut size is 10, and can be adjust between the range of 10 ~ 100. You can 79 + default size is 10, and can be adjust between the range of 10 ~ 100. You can 80 80 adjust the size like this: 81 81 82 82 # echo "<size>" > /sys/fs/ocfs2/<devname>/filecheck/set 83 83 84 84 Fixing stuff 85 85 ============ 86 - On receivng the inode, the filesystem would read the inode and the 86 + On receiving the inode, the filesystem would read the inode and the 87 87 file metadata. In case of errors, the filesystem would fix the errors 88 88 and report the problems it fixed in the kernel log. As a precautionary measure, 89 89 the inode must first be checked for errors before performing a final fix.
+22
Documentation/index.rst
··· 1 + .. The Linux Kernel documentation master file, created by 2 + sphinx-quickstart on Fri Feb 12 13:51:46 2016. 3 + You can adapt this file completely to your liking, but it should at least 4 + contain the root `toctree` directive. 5 + 6 + Welcome to The Linux Kernel's documentation! 7 + ============================================ 8 + 9 + Nothing for you to see here *yet*. Please move along. 10 + 11 + Contents: 12 + 13 + .. toctree:: 14 + :maxdepth: 2 15 + 16 + kernel-documentation 17 + 18 + Indices and tables 19 + ================== 20 + 21 + * :ref:`genindex` 22 + * :ref:`search`
+3
Documentation/kernel-doc-nano-HOWTO.txt
··· 1 + NOTE: this document is outdated and will eventually be removed. See 2 + Documentation/kernel-documentation.rst for current information. 3 + 1 4 kernel-doc nano-HOWTO 2 5 ===================== 3 6
+654
Documentation/kernel-documentation.rst
··· 1 + ========================== 2 + Linux Kernel Documentation 3 + ========================== 4 + 5 + Introduction 6 + ============ 7 + 8 + The Linux kernel uses `Sphinx`_ to generate pretty documentation from 9 + `reStructuredText`_ files under ``Documentation``. To build the documentation in 10 + HTML or PDF formats, use ``make htmldocs`` or ``make pdfdocs``. The generated 11 + documentation is placed in ``Documentation/output``. 12 + 13 + .. _Sphinx: http://www.sphinx-doc.org/ 14 + .. _reStructuredText: http://docutils.sourceforge.net/rst.html 15 + 16 + The reStructuredText files may contain directives to include structured 17 + documentation comments, or kernel-doc comments, from source files. Usually these 18 + are used to describe the functions and types and design of the code. The 19 + kernel-doc comments have some special structure and formatting, but beyond that 20 + they are also treated as reStructuredText. 21 + 22 + There is also the deprecated DocBook toolchain to generate documentation from 23 + DocBook XML template files under ``Documentation/DocBook``. The DocBook files 24 + are to be converted to reStructuredText, and the toolchain is slated to be 25 + removed. 26 + 27 + Finally, there are thousands of plain text documentation files scattered around 28 + ``Documentation``. Some of these will likely be converted to reStructuredText 29 + over time, but the bulk of them will remain in plain text. 30 + 31 + Sphinx Build 32 + ============ 33 + 34 + The usual way to generate the documentation is to run ``make htmldocs`` or 35 + ``make pdfdocs``. There are also other formats available, see the documentation 36 + section of ``make help``. The generated documentation is placed in 37 + format-specific subdirectories under ``Documentation/output``. 38 + 39 + To generate documentation, Sphinx (``sphinx-build``) must obviously be 40 + installed. For prettier HTML output, the Read the Docs Sphinx theme 41 + (``sphinx_rtd_theme``) is used if available. For PDF output, ``rst2pdf`` is also 42 + needed. All of these are widely available and packaged in distributions. 43 + 44 + To pass extra options to Sphinx, you can use the ``SPHINXOPTS`` make 45 + variable. For example, use ``make SPHINXOPTS=-v htmldocs`` to get more verbose 46 + output. 47 + 48 + To remove the generated documentation, run ``make cleandocs``. 49 + 50 + Writing Documentation 51 + ===================== 52 + 53 + Adding new documentation can be as simple as: 54 + 55 + 1. Add a new ``.rst`` file somewhere under ``Documentation``. 56 + 2. Refer to it from the Sphinx main `TOC tree`_ in ``Documentation/index.rst``. 57 + 58 + .. _TOC tree: http://www.sphinx-doc.org/en/stable/markup/toctree.html 59 + 60 + This is usually good enough for simple documentation (like the one you're 61 + reading right now), but for larger documents it may be advisable to create a 62 + subdirectory (or use an existing one). For example, the graphics subsystem 63 + documentation is under ``Documentation/gpu``, split to several ``.rst`` files, 64 + and has a separate ``index.rst`` (with a ``toctree`` of its own) referenced from 65 + the main index. 66 + 67 + See the documentation for `Sphinx`_ and `reStructuredText`_ on what you can do 68 + with them. In particular, the Sphinx `reStructuredText Primer`_ is a good place 69 + to get started with reStructuredText. There are also some `Sphinx specific 70 + markup constructs`_. 71 + 72 + .. _reStructuredText Primer: http://www.sphinx-doc.org/en/stable/rest.html 73 + .. _Sphinx specific markup constructs: http://www.sphinx-doc.org/en/stable/markup/index.html 74 + 75 + Specific guidelines for the kernel documentation 76 + ------------------------------------------------ 77 + 78 + Here are some specific guidelines for the kernel documentation: 79 + 80 + * Please don't go overboard with reStructuredText markup. Keep it simple. 81 + 82 + * Please stick to this order of heading adornments: 83 + 84 + 1. ``=`` with overline for document title:: 85 + 86 + ============== 87 + Document title 88 + ============== 89 + 90 + 2. ``=`` for chapters:: 91 + 92 + Chapters 93 + ======== 94 + 95 + 3. ``-`` for sections:: 96 + 97 + Section 98 + ------- 99 + 100 + 4. ``~`` for subsections:: 101 + 102 + Subsection 103 + ~~~~~~~~~~ 104 + 105 + Although RST doesn't mandate a specific order ("Rather than imposing a fixed 106 + number and order of section title adornment styles, the order enforced will be 107 + the order as encountered."), having the higher levels the same overall makes 108 + it easier to follow the documents. 109 + 110 + list tables 111 + ----------- 112 + 113 + We recommend the use of *list table* formats. The *list table* formats are 114 + double-stage lists. Compared to the ASCII-art they might not be as 115 + comfortable for 116 + readers of the text files. Their advantage is that they are easy to 117 + create or modify and that the diff of a modification is much more meaningful, 118 + because it is limited to the modified content. 119 + 120 + The ``flat-table`` is a double-stage list similar to the ``list-table`` with 121 + some additional features: 122 + 123 + * column-span: with the role ``cspan`` a cell can be extended through 124 + additional columns 125 + 126 + * row-span: with the role ``rspan`` a cell can be extended through 127 + additional rows 128 + 129 + * auto span rightmost cell of a table row over the missing cells on the right 130 + side of that table-row. With Option ``:fill-cells:`` this behavior can 131 + changed from *auto span* to *auto fill*, which automatically inserts (empty) 132 + cells instead of spanning the last cell. 133 + 134 + options: 135 + 136 + * ``:header-rows:`` [int] count of header rows 137 + * ``:stub-columns:`` [int] count of stub columns 138 + * ``:widths:`` [[int] [int] ... ] widths of columns 139 + * ``:fill-cells:`` instead of auto-spanning missing cells, insert missing cells 140 + 141 + roles: 142 + 143 + * ``:cspan:`` [int] additional columns (*morecols*) 144 + * ``:rspan:`` [int] additional rows (*morerows*) 145 + 146 + The example below shows how to use this markup. The first level of the staged 147 + list is the *table-row*. In the *table-row* there is only one markup allowed, 148 + the list of the cells in this *table-row*. Exceptions are *comments* ( ``..`` ) 149 + and *targets* (e.g. a ref to ``:ref:`last row <last row>``` / :ref:`last row 150 + <last row>`). 151 + 152 + .. code-block:: rst 153 + 154 + .. flat-table:: table title 155 + :widths: 2 1 1 3 156 + 157 + * - head col 1 158 + - head col 2 159 + - head col 3 160 + - head col 4 161 + 162 + * - column 1 163 + - field 1.1 164 + - field 1.2 with autospan 165 + 166 + * - column 2 167 + - field 2.1 168 + - :rspan:`1` :cspan:`1` field 2.2 - 3.3 169 + 170 + * .. _`last row`: 171 + 172 + - column 3 173 + 174 + Rendered as: 175 + 176 + .. flat-table:: table title 177 + :widths: 2 1 1 3 178 + 179 + * - head col 1 180 + - head col 2 181 + - head col 3 182 + - head col 4 183 + 184 + * - column 1 185 + - field 1.1 186 + - field 1.2 with autospan 187 + 188 + * - column 2 189 + - field 2.1 190 + - :rspan:`1` :cspan:`1` field 2.2 - 3.3 191 + 192 + * .. _`last row`: 193 + 194 + - column 3 195 + 196 + 197 + Including kernel-doc comments 198 + ============================= 199 + 200 + The Linux kernel source files may contain structured documentation comments, or 201 + kernel-doc comments to describe the functions and types and design of the 202 + code. The documentation comments may be included to any of the reStructuredText 203 + documents using a dedicated kernel-doc Sphinx directive extension. 204 + 205 + The kernel-doc directive is of the format:: 206 + 207 + .. kernel-doc:: source 208 + :option: 209 + 210 + The *source* is the path to a source file, relative to the kernel source 211 + tree. The following directive options are supported: 212 + 213 + export: *[source-pattern ...]* 214 + Include documentation for all functions in *source* that have been exported 215 + using ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL`` either in *source* or in any 216 + of the files specified by *source-pattern*. 217 + 218 + The *source-pattern* is useful when the kernel-doc comments have been placed 219 + in header files, while ``EXPORT_SYMBOL`` and ``EXPORT_SYMBOL_GPL`` are next to 220 + the function definitions. 221 + 222 + Examples:: 223 + 224 + .. kernel-doc:: lib/bitmap.c 225 + :export: 226 + 227 + .. kernel-doc:: include/net/mac80211.h 228 + :export: net/mac80211/*.c 229 + 230 + internal: *[source-pattern ...]* 231 + Include documentation for all functions and types in *source* that have 232 + **not** been exported using ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL`` either 233 + in *source* or in any of the files specified by *source-pattern*. 234 + 235 + Example:: 236 + 237 + .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c 238 + :internal: 239 + 240 + doc: *title* 241 + Include documentation for the ``DOC:`` paragraph identified by *title* in 242 + *source*. Spaces are allowed in *title*; do not quote the *title*. The *title* 243 + is only used as an identifier for the paragraph, and is not included in the 244 + output. Please make sure to have an appropriate heading in the enclosing 245 + reStructuredText document. 246 + 247 + Example:: 248 + 249 + .. kernel-doc:: drivers/gpu/drm/i915/intel_audio.c 250 + :doc: High Definition Audio over HDMI and Display Port 251 + 252 + functions: *function* *[...]* 253 + Include documentation for each *function* in *source*. 254 + 255 + Example:: 256 + 257 + .. kernel-doc:: lib/bitmap.c 258 + :functions: bitmap_parselist bitmap_parselist_user 259 + 260 + Without options, the kernel-doc directive includes all documentation comments 261 + from the source file. 262 + 263 + The kernel-doc extension is included in the kernel source tree, at 264 + ``Documentation/sphinx/kernel-doc.py``. Internally, it uses the 265 + ``scripts/kernel-doc`` script to extract the documentation comments from the 266 + source. 267 + 268 + Writing kernel-doc comments 269 + =========================== 270 + 271 + In order to provide embedded, "C" friendly, easy to maintain, but consistent and 272 + extractable overview, function and type documentation, the Linux kernel has 273 + adopted a consistent style for documentation comments. The format for this 274 + documentation is called the kernel-doc format, described below. This style 275 + embeds the documentation within the source files, using a few simple conventions 276 + for adding documentation paragraphs and documenting functions and their 277 + parameters, structures and unions and their members, enumerations, and typedefs. 278 + 279 + .. note:: The kernel-doc format is deceptively similar to gtk-doc or Doxygen, 280 + yet distinctively different, for historical reasons. The kernel source 281 + contains tens of thousands of kernel-doc comments. Please stick to the style 282 + described here. 283 + 284 + The ``scripts/kernel-doc`` script is used by the Sphinx kernel-doc extension in 285 + the documentation build to extract this embedded documentation into the various 286 + HTML, PDF, and other format documents. 287 + 288 + In order to provide good documentation of kernel functions and data structures, 289 + please use the following conventions to format your kernel-doc comments in the 290 + Linux kernel source. 291 + 292 + How to format kernel-doc comments 293 + --------------------------------- 294 + 295 + The opening comment mark ``/**`` is reserved for kernel-doc comments. Only 296 + comments so marked will be considered by the ``kernel-doc`` tool. Use it only 297 + for comment blocks that contain kernel-doc formatted comments. The usual ``*/`` 298 + should be used as the closing comment marker. The lines in between should be 299 + prefixed by `` * `` (space star space). 300 + 301 + The function and type kernel-doc comments should be placed just before the 302 + function or type being described. The overview kernel-doc comments may be freely 303 + placed at the top indentation level. 304 + 305 + Example kernel-doc function comment:: 306 + 307 + /** 308 + * foobar() - Brief description of foobar. 309 + * @arg: Description of argument of foobar. 310 + * 311 + * Longer description of foobar. 312 + * 313 + * Return: Description of return value of foobar. 314 + */ 315 + int foobar(int arg) 316 + 317 + The format is similar for documentation for structures, enums, paragraphs, 318 + etc. See the sections below for details. 319 + 320 + The kernel-doc structure is extracted from the comments, and proper `Sphinx C 321 + Domain`_ function and type descriptions with anchors are generated for them. The 322 + descriptions are filtered for special kernel-doc highlights and 323 + cross-references. See below for details. 324 + 325 + .. _Sphinx C Domain: http://www.sphinx-doc.org/en/stable/domains.html 326 + 327 + Highlights and cross-references 328 + ------------------------------- 329 + 330 + The following special patterns are recognized in the kernel-doc comment 331 + descriptive text and converted to proper reStructuredText markup and `Sphinx C 332 + Domain`_ references. 333 + 334 + .. attention:: The below are **only** recognized within kernel-doc comments, 335 + **not** within normal reStructuredText documents. 336 + 337 + ``funcname()`` 338 + Function reference. 339 + 340 + ``@parameter`` 341 + Name of a function parameter. (No cross-referencing, just formatting.) 342 + 343 + ``%CONST`` 344 + Name of a constant. (No cross-referencing, just formatting.) 345 + 346 + ``$ENVVAR`` 347 + Name of an environment variable. (No cross-referencing, just formatting.) 348 + 349 + ``&struct name`` 350 + Structure reference. 351 + 352 + ``&enum name`` 353 + Enum reference. 354 + 355 + ``&typedef name`` 356 + Typedef reference. 357 + 358 + ``&struct_name->member`` or ``&struct_name.member`` 359 + Structure or union member reference. The cross-reference will be to the struct 360 + or union definition, not the member directly. 361 + 362 + ``&name`` 363 + A generic type reference. Prefer using the full reference described above 364 + instead. This is mostly for legacy comments. 365 + 366 + Cross-referencing from reStructuredText 367 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 368 + 369 + .. highlight:: none 370 + 371 + To cross-reference the functions and types defined in the kernel-doc comments 372 + from reStructuredText documents, please use the `Sphinx C Domain`_ 373 + references. For example:: 374 + 375 + See function :c:func:`foo` and struct/union/enum/typedef :c:type:`bar`. 376 + 377 + While the type reference works with just the type name, without the 378 + struct/union/enum/typedef part in front, you may want to use:: 379 + 380 + See :c:type:`struct foo <foo>`. 381 + See :c:type:`union bar <bar>`. 382 + See :c:type:`enum baz <baz>`. 383 + See :c:type:`typedef meh <meh>`. 384 + 385 + This will produce prettier links, and is in line with how kernel-doc does the 386 + cross-references. 387 + 388 + For further details, please refer to the `Sphinx C Domain`_ documentation. 389 + 390 + Function documentation 391 + ---------------------- 392 + 393 + .. highlight:: c 394 + 395 + The general format of a function and function-like macro kernel-doc comment is:: 396 + 397 + /** 398 + * function_name() - Brief description of function. 399 + * @arg1: Describe the first argument. 400 + * @arg2: Describe the second argument. 401 + * One can provide multiple line descriptions 402 + * for arguments. 403 + * 404 + * A longer description, with more discussion of the function function_name() 405 + * that might be useful to those using or modifying it. Begins with an 406 + * empty comment line, and may include additional embedded empty 407 + * comment lines. 408 + * 409 + * The longer description may have multiple paragraphs. 410 + * 411 + * Return: Describe the return value of foobar. 412 + * 413 + * The return value description can also have multiple paragraphs, and should 414 + * be placed at the end of the comment block. 415 + */ 416 + 417 + The brief description following the function name may span multiple lines, and 418 + ends with an ``@argument:`` description, a blank comment line, or the end of the 419 + comment block. 420 + 421 + The kernel-doc function comments describe each parameter to the function, in 422 + order, with the ``@argument:`` descriptions. The ``@argument:`` descriptions 423 + must begin on the very next line following the opening brief function 424 + description line, with no intervening blank comment lines. The ``@argument:`` 425 + descriptions may span multiple lines. The continuation lines may contain 426 + indentation. If a function parameter is ``...`` (varargs), it should be listed 427 + in kernel-doc notation as: ``@...:``. 428 + 429 + The return value, if any, should be described in a dedicated section at the end 430 + of the comment starting with "Return:". 431 + 432 + Structure, union, and enumeration documentation 433 + ----------------------------------------------- 434 + 435 + The general format of a struct, union, and enum kernel-doc comment is:: 436 + 437 + /** 438 + * struct struct_name - Brief description. 439 + * @member_name: Description of member member_name. 440 + * 441 + * Description of the structure. 442 + */ 443 + 444 + Below, "struct" is used to mean structs, unions and enums, and "member" is used 445 + to mean struct and union members as well as enumerations in an enum. 446 + 447 + The brief description following the structure name may span multiple lines, and 448 + ends with a ``@member:`` description, a blank comment line, or the end of the 449 + comment block. 450 + 451 + The kernel-doc data structure comments describe each member of the structure, in 452 + order, with the ``@member:`` descriptions. The ``@member:`` descriptions must 453 + begin on the very next line following the opening brief function description 454 + line, with no intervening blank comment lines. The ``@member:`` descriptions may 455 + span multiple lines. The continuation lines may contain indentation. 456 + 457 + In-line member documentation comments 458 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 459 + 460 + The structure members may also be documented in-line within the definition:: 461 + 462 + /** 463 + * struct foo - Brief description. 464 + * @foo: The Foo member. 465 + */ 466 + struct foo { 467 + int foo; 468 + /** 469 + * @bar: The Bar member. 470 + */ 471 + int bar; 472 + /** 473 + * @baz: The Baz member. 474 + * 475 + * Here, the member description may contain several paragraphs. 476 + */ 477 + int baz; 478 + } 479 + 480 + Private members 481 + ~~~~~~~~~~~~~~~ 482 + 483 + Inside a struct description, you can use the "private:" and "public:" comment 484 + tags. Structure fields that are inside a "private:" area are not listed in the 485 + generated output documentation. The "private:" and "public:" tags must begin 486 + immediately following a ``/*`` comment marker. They may optionally include 487 + comments between the ``:`` and the ending ``*/`` marker. 488 + 489 + Example:: 490 + 491 + /** 492 + * struct my_struct - short description 493 + * @a: first member 494 + * @b: second member 495 + * 496 + * Longer description 497 + */ 498 + struct my_struct { 499 + int a; 500 + int b; 501 + /* private: internal use only */ 502 + int c; 503 + }; 504 + 505 + 506 + Typedef documentation 507 + --------------------- 508 + 509 + The general format of a typedef kernel-doc comment is:: 510 + 511 + /** 512 + * typedef type_name - Brief description. 513 + * 514 + * Description of the type. 515 + */ 516 + 517 + Overview documentation comments 518 + ------------------------------- 519 + 520 + To facilitate having source code and comments close together, you can include 521 + kernel-doc documentation blocks that are free-form comments instead of being 522 + kernel-doc for functions, structures, unions, enums, or typedefs. This could be 523 + used for something like a theory of operation for a driver or library code, for 524 + example. 525 + 526 + This is done by using a ``DOC:`` section keyword with a section title. 527 + 528 + The general format of an overview or high-level documentation comment is:: 529 + 530 + /** 531 + * DOC: Theory of Operation 532 + * 533 + * The whizbang foobar is a dilly of a gizmo. It can do whatever you 534 + * want it to do, at any time. It reads your mind. Here's how it works. 535 + * 536 + * foo bar splat 537 + * 538 + * The only drawback to this gizmo is that is can sometimes damage 539 + * hardware, software, or its subject(s). 540 + */ 541 + 542 + The title following ``DOC:`` acts as a heading within the source file, but also 543 + as an identifier for extracting the documentation comment. Thus, the title must 544 + be unique within the file. 545 + 546 + Recommendations 547 + --------------- 548 + 549 + We definitely need kernel-doc formatted documentation for functions that are 550 + exported to loadable modules using ``EXPORT_SYMBOL`` or ``EXPORT_SYMBOL_GPL``. 551 + 552 + We also look to provide kernel-doc formatted documentation for functions 553 + externally visible to other kernel files (not marked "static"). 554 + 555 + We also recommend providing kernel-doc formatted documentation for private (file 556 + "static") routines, for consistency of kernel source code layout. But this is 557 + lower priority and at the discretion of the MAINTAINER of that kernel source 558 + file. 559 + 560 + Data structures visible in kernel include files should also be documented using 561 + kernel-doc formatted comments. 562 + 563 + DocBook XML [DEPRECATED] 564 + ======================== 565 + 566 + .. attention:: 567 + 568 + This section describes the deprecated DocBook XML toolchain. Please do not 569 + create new DocBook XML template files. Please consider converting existing 570 + DocBook XML templates files to Sphinx/reStructuredText. 571 + 572 + Converting DocBook to Sphinx 573 + ---------------------------- 574 + 575 + .. highlight:: none 576 + 577 + Over time, we expect all of the documents under ``Documentation/DocBook`` to be 578 + converted to Sphinx and reStructuredText. For most DocBook XML documents, a good 579 + enough solution is to use the simple ``Documentation/sphinx/tmplcvt`` script, 580 + which uses ``pandoc`` under the hood. For example:: 581 + 582 + $ cd Documentation/sphinx 583 + $ ./tmplcvt ../DocBook/in.tmpl ../out.rst 584 + 585 + Then edit the resulting rst files to fix any remaining issues, and add the 586 + document in the ``toctree`` in ``Documentation/index.rst``. 587 + 588 + Components of the kernel-doc system 589 + ----------------------------------- 590 + 591 + Many places in the source tree have extractable documentation in the form of 592 + block comments above functions. The components of this system are: 593 + 594 + - ``scripts/kernel-doc`` 595 + 596 + This is a perl script that hunts for the block comments and can mark them up 597 + directly into reStructuredText, DocBook, man, text, and HTML. (No, not 598 + texinfo.) 599 + 600 + - ``Documentation/DocBook/*.tmpl`` 601 + 602 + These are XML template files, which are normal XML files with special 603 + place-holders for where the extracted documentation should go. 604 + 605 + - ``scripts/docproc.c`` 606 + 607 + This is a program for converting XML template files into XML files. When a 608 + file is referenced it is searched for symbols exported (EXPORT_SYMBOL), to be 609 + able to distinguish between internal and external functions. 610 + 611 + It invokes kernel-doc, giving it the list of functions that are to be 612 + documented. 613 + 614 + Additionally it is used to scan the XML template files to locate all the files 615 + referenced herein. This is used to generate dependency information as used by 616 + make. 617 + 618 + - ``Makefile`` 619 + 620 + The targets 'xmldocs', 'psdocs', 'pdfdocs', and 'htmldocs' are used to build 621 + DocBook XML files, PostScript files, PDF files, and html files in 622 + Documentation/DocBook. The older target 'sgmldocs' is equivalent to 'xmldocs'. 623 + 624 + - ``Documentation/DocBook/Makefile`` 625 + 626 + This is where C files are associated with SGML templates. 627 + 628 + How to use kernel-doc comments in DocBook XML template files 629 + ------------------------------------------------------------ 630 + 631 + DocBook XML template files (\*.tmpl) are like normal XML files, except that they 632 + can contain escape sequences where extracted documentation should be inserted. 633 + 634 + ``!E<filename>`` is replaced by the documentation, in ``<filename>``, for 635 + functions that are exported using ``EXPORT_SYMBOL``: the function list is 636 + collected from files listed in ``Documentation/DocBook/Makefile``. 637 + 638 + ``!I<filename>`` is replaced by the documentation for functions that are **not** 639 + exported using ``EXPORT_SYMBOL``. 640 + 641 + ``!D<filename>`` is used to name additional files to search for functions 642 + exported using ``EXPORT_SYMBOL``. 643 + 644 + ``!F<filename> <function [functions...]>`` is replaced by the documentation, in 645 + ``<filename>``, for the functions listed. 646 + 647 + ``!P<filename> <section title>`` is replaced by the contents of the ``DOC:`` 648 + section titled ``<section title>`` from ``<filename>``. Spaces are allowed in 649 + ``<section title>``; do not quote the ``<section title>``. 650 + 651 + ``!C<filename>`` is replaced by nothing, but makes the tools check that all DOC: 652 + sections and documented functions, symbols, etc. are used. This makes sense to 653 + use when you use ``!F`` or ``!P`` only and want to verify that all documentation 654 + is included.
+3 -2
Documentation/kernel-parameters.txt
··· 3996 3996 3997 3997 trace_event=[event-list] 3998 3998 [FTRACE] Set and start specified trace events in order 3999 - to facilitate early boot debugging. 4000 - See also Documentation/trace/events.txt 3999 + to facilitate early boot debugging. The event-list is a 4000 + comma separated list of trace events to enable. See 4001 + also Documentation/trace/events.txt 4001 4002 4002 4003 trace_options=[option-list] 4003 4004 [FTRACE] Enable or disable tracer options at boot.
+1 -1
Documentation/md.txt
··· 602 602 603 603 stripe_cache_size (currently raid5 only) 604 604 number of entries in the stripe cache. This is writable, but 605 - there are upper and lower limits (32768, 16). Default is 128. 605 + there are upper and lower limits (32768, 17). Default is 256. 606 606 strip_cache_active (currently raid5 only) 607 607 number of active entries in the stripe cache 608 608 preread_bypass_threshold (currently raid5 only)
+2 -2
Documentation/mic/mpssd/mpssd.c
··· 1538 1538 1539 1539 len = snprintf(buffer, PATH_MAX, 1540 1540 "clocksource=tsc highres=off nohz=off "); 1541 - len += snprintf(buffer + len, PATH_MAX, 1541 + len += snprintf(buffer + len, PATH_MAX - len, 1542 1542 "cpufreq_on;corec6_off;pc3_off;pc6_off "); 1543 - len += snprintf(buffer + len, PATH_MAX, 1543 + len += snprintf(buffer + len, PATH_MAX - len, 1544 1544 "ifcfg=static;address,172.31.%d.1;netmask,255.255.255.0", 1545 1545 mic->id + 1); 1546 1546
+18 -10
Documentation/security/self-protection.txt
··· 183 183 ### Canaries, blinding, and other secrets 184 184 185 185 It should be noted that things like the stack canary discussed earlier 186 - are technically statistical defenses, since they rely on a (leakable) 187 - secret value. 186 + are technically statistical defenses, since they rely on a secret value, 187 + and such values may become discoverable through an information exposure 188 + flaw. 188 189 189 190 Blinding literal values for things like JITs, where the executable 190 191 contents may be partially under the control of userspace, need a similar ··· 200 199 Since the location of kernel memory is almost always instrumental in 201 200 mounting a successful attack, making the location non-deterministic 202 201 raises the difficulty of an exploit. (Note that this in turn makes 203 - the value of leaks higher, since they may be used to discover desired 204 - memory locations.) 202 + the value of information exposures higher, since they may be used to 203 + discover desired memory locations.) 205 204 206 205 #### Text and module base 207 206 ··· 223 222 Much of the kernel's dynamic memory (e.g. kmalloc, vmalloc, etc) ends up 224 223 being relatively deterministic in layout due to the order of early-boot 225 224 initializations. If the base address of these areas is not the same 226 - between boots, targeting them is frustrated, requiring a leak specific 227 - to the region. 225 + between boots, targeting them is frustrated, requiring an information 226 + exposure specific to the region. 227 + 228 + #### Structure layout 229 + 230 + By performing a per-build randomization of the layout of sensitive 231 + structures, attacks must either be tuned to known kernel builds or expose 232 + enough kernel memory to determine structure layouts before manipulating 233 + them. 228 234 229 235 230 - ## Preventing Leaks 236 + ## Preventing Information Exposures 231 237 232 238 Since the locations of sensitive structures are the primary target for 233 - attacks, it is important to defend against leaks of both kernel memory 239 + attacks, it is important to defend against exposure of both kernel memory 234 240 addresses and kernel memory contents (since they may contain kernel 235 241 addresses or other sensitive things like canary values). 236 242 ··· 258 250 When releasing memory, it is best to poison the contents (clear stack on 259 251 syscall return, wipe heap memory on a free), to avoid reuse attacks that 260 252 rely on the old contents of memory. This frustrates many uninitialized 261 - variable attacks, stack info leaks, heap info leaks, and use-after-free 262 - attacks. 253 + variable attacks, stack content exposures, heap content exposures, and 254 + use-after-free attacks. 263 255 264 256 ### Destination tracking 265 257
+18
Documentation/sphinx/convert_template.sed
··· 1 + # 2 + # Pandoc doesn't grok <function> or <structname>, so convert them 3 + # ahead of time. 4 + # 5 + # Use the following escapes to pass through pandoc: 6 + # $bq = "`" 7 + # $lt = "<" 8 + # $gt = ">" 9 + # 10 + s%<function>\([^<(]\+\)()</function>%:c:func:$bq\1()$bq%g 11 + s%<function>\([^<(]\+\)</function>%:c:func:$bq\1()$bq%g 12 + s%<structname>struct *\([^<]\+\)</structname>%:c:type:$bqstruct \1 $lt\1$gt$bq%g 13 + s%struct <structname>\([^<]\+\)</structname>%:c:type:$bqstruct \1 $lt\1$gt$bq%g 14 + s%<structname>\([^<]\+\)</structname>%:c:type:$bqstruct \1 $lt\1$gt$bq%g 15 + # 16 + # Wrap docproc directives in para and code blocks. 17 + # 18 + s%^\(!.*\)$%<para><code>DOCPROC: \1</code></para>%
+141
Documentation/sphinx/kernel-doc.py
··· 1 + # coding=utf-8 2 + # 3 + # Copyright © 2016 Intel Corporation 4 + # 5 + # Permission is hereby granted, free of charge, to any person obtaining a 6 + # copy of this software and associated documentation files (the "Software"), 7 + # to deal in the Software without restriction, including without limitation 8 + # the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 + # and/or sell copies of the Software, and to permit persons to whom the 10 + # Software is furnished to do so, subject to the following conditions: 11 + # 12 + # The above copyright notice and this permission notice (including the next 13 + # paragraph) shall be included in all copies or substantial portions of the 14 + # Software. 15 + # 16 + # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 + # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 + # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 + # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 + # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 22 + # IN THE SOFTWARE. 23 + # 24 + # Authors: 25 + # Jani Nikula <jani.nikula@intel.com> 26 + # 27 + # Please make sure this works on both python2 and python3. 28 + # 29 + 30 + import os 31 + import subprocess 32 + import sys 33 + import re 34 + import glob 35 + 36 + from docutils import nodes, statemachine 37 + from docutils.statemachine import ViewList 38 + from docutils.parsers.rst import directives 39 + from sphinx.util.compat import Directive 40 + from sphinx.ext.autodoc import AutodocReporter 41 + 42 + class KernelDocDirective(Directive): 43 + """Extract kernel-doc comments from the specified file""" 44 + required_argument = 1 45 + optional_arguments = 4 46 + option_spec = { 47 + 'doc': directives.unchanged_required, 48 + 'functions': directives.unchanged_required, 49 + 'export': directives.unchanged, 50 + 'internal': directives.unchanged, 51 + } 52 + has_content = False 53 + 54 + def run(self): 55 + env = self.state.document.settings.env 56 + cmd = [env.config.kerneldoc_bin, '-rst', '-enable-lineno'] 57 + 58 + filename = env.config.kerneldoc_srctree + '/' + self.arguments[0] 59 + export_file_patterns = [] 60 + 61 + # Tell sphinx of the dependency 62 + env.note_dependency(os.path.abspath(filename)) 63 + 64 + tab_width = self.options.get('tab-width', self.state.document.settings.tab_width) 65 + 66 + # FIXME: make this nicer and more robust against errors 67 + if 'export' in self.options: 68 + cmd += ['-export'] 69 + export_file_patterns = str(self.options.get('export')).split() 70 + elif 'internal' in self.options: 71 + cmd += ['-internal'] 72 + export_file_patterns = str(self.options.get('internal')).split() 73 + elif 'doc' in self.options: 74 + cmd += ['-function', str(self.options.get('doc'))] 75 + elif 'functions' in self.options: 76 + for f in str(self.options.get('functions')).split(): 77 + cmd += ['-function', f] 78 + 79 + for pattern in export_file_patterns: 80 + for f in glob.glob(env.config.kerneldoc_srctree + '/' + pattern): 81 + env.note_dependency(os.path.abspath(f)) 82 + cmd += ['-export-file', f] 83 + 84 + cmd += [filename] 85 + 86 + try: 87 + env.app.verbose('calling kernel-doc \'%s\'' % (" ".join(cmd))) 88 + 89 + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) 90 + out, err = p.communicate() 91 + 92 + # python2 needs conversion to unicode. 93 + # python3 with universal_newlines=True returns strings. 94 + if sys.version_info.major < 3: 95 + out, err = unicode(out, 'utf-8'), unicode(err, 'utf-8') 96 + 97 + if p.returncode != 0: 98 + sys.stderr.write(err) 99 + 100 + env.app.warn('kernel-doc \'%s\' failed with return code %d' % (" ".join(cmd), p.returncode)) 101 + return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))] 102 + elif env.config.kerneldoc_verbosity > 0: 103 + sys.stderr.write(err) 104 + 105 + lines = statemachine.string2lines(out, tab_width, convert_whitespace=True) 106 + result = ViewList() 107 + 108 + lineoffset = 0; 109 + line_regex = re.compile("^#define LINENO ([0-9]+)$") 110 + for line in lines: 111 + match = line_regex.search(line) 112 + if match: 113 + # sphinx counts lines from 0 114 + lineoffset = int(match.group(1)) - 1 115 + # we must eat our comments since the upset the markup 116 + else: 117 + result.append(line, filename, lineoffset) 118 + lineoffset += 1 119 + 120 + node = nodes.section() 121 + buf = self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter 122 + self.state.memo.reporter = AutodocReporter(result, self.state.memo.reporter) 123 + self.state.memo.title_styles, self.state.memo.section_level = [], 0 124 + try: 125 + self.state.nested_parse(result, 0, node, match_titles=1) 126 + finally: 127 + self.state.memo.title_styles, self.state.memo.section_level, self.state.memo.reporter = buf 128 + 129 + return node.children 130 + 131 + except Exception as e: # pylint: disable=W0703 132 + env.app.warn('kernel-doc \'%s\' processing failed with: %s' % 133 + (" ".join(cmd), str(e))) 134 + return [nodes.error(None, nodes.paragraph(text = "kernel-doc missing"))] 135 + 136 + def setup(app): 137 + app.add_config_value('kerneldoc_bin', None, 'env') 138 + app.add_config_value('kerneldoc_srctree', None, 'env') 139 + app.add_config_value('kerneldoc_verbosity', 1, 'env') 140 + 141 + app.add_directive('kernel-doc', KernelDocDirective)
+23
Documentation/sphinx/post_convert.sed
··· 1 + # 2 + # Unescape. 3 + # 4 + s/$bq/`/g 5 + s/$lt/</g 6 + s/$gt/>/g 7 + # 8 + # pandoc thinks that both "_" needs to be escaped. Remove the extra 9 + # backslashes. 10 + # 11 + s/\\_/_/g 12 + # 13 + # Unwrap docproc directives. 14 + # 15 + s/^``DOCPROC: !E\(.*\)``$/.. kernel-doc:: \1\n :export:/ 16 + s/^``DOCPROC: !I\(.*\)``$/.. kernel-doc:: \1\n :internal:/ 17 + s/^``DOCPROC: !F\([^ ]*\) \(.*\)``$/.. kernel-doc:: \1\n :functions: \2/ 18 + s/^``DOCPROC: !P\([^ ]*\) \(.*\)``$/.. kernel-doc:: \1\n :doc: \2/ 19 + s/^``DOCPROC: \(!.*\)``$/.. WARNING: DOCPROC directive not supported: \1/ 20 + # 21 + # Trim trailing whitespace. 22 + # 23 + s/[[:space:]]*$//
+365
Documentation/sphinx/rstFlatTable.py
··· 1 + #!/usr/bin/env python3 2 + # -*- coding: utf-8; mode: python -*- 3 + # pylint: disable=C0330, R0903, R0912 4 + 5 + u""" 6 + flat-table 7 + ~~~~~~~~~~ 8 + 9 + Implementation of the ``flat-table`` reST-directive. 10 + 11 + :copyright: Copyright (C) 2016 Markus Heiser 12 + :license: GPL Version 2, June 1991 see linux/COPYING for details. 13 + 14 + The ``flat-table`` (:py:class:`FlatTable`) is a double-stage list similar to 15 + the ``list-table`` with some additional features: 16 + 17 + * *column-span*: with the role ``cspan`` a cell can be extended through 18 + additional columns 19 + 20 + * *row-span*: with the role ``rspan`` a cell can be extended through 21 + additional rows 22 + 23 + * *auto span* rightmost cell of a table row over the missing cells on the 24 + right side of that table-row. With Option ``:fill-cells:`` this behavior 25 + can changed from *auto span* to *auto fill*, which automaticly inserts 26 + (empty) cells instead of spanning the last cell. 27 + 28 + Options: 29 + 30 + * header-rows: [int] count of header rows 31 + * stub-columns: [int] count of stub columns 32 + * widths: [[int] [int] ... ] widths of columns 33 + * fill-cells: instead of autospann missing cells, insert missing cells 34 + 35 + roles: 36 + 37 + * cspan: [int] additionale columns (*morecols*) 38 + * rspan: [int] additionale rows (*morerows*) 39 + """ 40 + 41 + # ============================================================================== 42 + # imports 43 + # ============================================================================== 44 + 45 + import sys 46 + 47 + from docutils import nodes 48 + from docutils.parsers.rst import directives, roles 49 + from docutils.parsers.rst.directives.tables import Table 50 + from docutils.utils import SystemMessagePropagation 51 + 52 + # ============================================================================== 53 + # common globals 54 + # ============================================================================== 55 + 56 + # The version numbering follows numbering of the specification 57 + # (Documentation/books/kernel-doc-HOWTO). 58 + __version__ = '1.0' 59 + 60 + PY3 = sys.version_info[0] == 3 61 + PY2 = sys.version_info[0] == 2 62 + 63 + if PY3: 64 + # pylint: disable=C0103, W0622 65 + unicode = str 66 + basestring = str 67 + 68 + # ============================================================================== 69 + def setup(app): 70 + # ============================================================================== 71 + 72 + app.add_directive("flat-table", FlatTable) 73 + roles.register_local_role('cspan', c_span) 74 + roles.register_local_role('rspan', r_span) 75 + 76 + # ============================================================================== 77 + def c_span(name, rawtext, text, lineno, inliner, options=None, content=None): 78 + # ============================================================================== 79 + # pylint: disable=W0613 80 + 81 + options = options if options is not None else {} 82 + content = content if content is not None else [] 83 + nodelist = [colSpan(span=int(text))] 84 + msglist = [] 85 + return nodelist, msglist 86 + 87 + # ============================================================================== 88 + def r_span(name, rawtext, text, lineno, inliner, options=None, content=None): 89 + # ============================================================================== 90 + # pylint: disable=W0613 91 + 92 + options = options if options is not None else {} 93 + content = content if content is not None else [] 94 + nodelist = [rowSpan(span=int(text))] 95 + msglist = [] 96 + return nodelist, msglist 97 + 98 + 99 + # ============================================================================== 100 + class rowSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321 101 + class colSpan(nodes.General, nodes.Element): pass # pylint: disable=C0103,C0321 102 + # ============================================================================== 103 + 104 + # ============================================================================== 105 + class FlatTable(Table): 106 + # ============================================================================== 107 + 108 + u"""FlatTable (``flat-table``) directive""" 109 + 110 + option_spec = { 111 + 'name': directives.unchanged 112 + , 'class': directives.class_option 113 + , 'header-rows': directives.nonnegative_int 114 + , 'stub-columns': directives.nonnegative_int 115 + , 'widths': directives.positive_int_list 116 + , 'fill-cells' : directives.flag } 117 + 118 + def run(self): 119 + 120 + if not self.content: 121 + error = self.state_machine.reporter.error( 122 + 'The "%s" directive is empty; content required.' % self.name, 123 + nodes.literal_block(self.block_text, self.block_text), 124 + line=self.lineno) 125 + return [error] 126 + 127 + title, messages = self.make_title() 128 + node = nodes.Element() # anonymous container for parsing 129 + self.state.nested_parse(self.content, self.content_offset, node) 130 + 131 + tableBuilder = ListTableBuilder(self) 132 + tableBuilder.parseFlatTableNode(node) 133 + tableNode = tableBuilder.buildTableNode() 134 + # SDK.CONSOLE() # print --> tableNode.asdom().toprettyxml() 135 + if title: 136 + tableNode.insert(0, title) 137 + return [tableNode] + messages 138 + 139 + 140 + # ============================================================================== 141 + class ListTableBuilder(object): 142 + # ============================================================================== 143 + 144 + u"""Builds a table from a double-stage list""" 145 + 146 + def __init__(self, directive): 147 + self.directive = directive 148 + self.rows = [] 149 + self.max_cols = 0 150 + 151 + def buildTableNode(self): 152 + 153 + colwidths = self.directive.get_column_widths(self.max_cols) 154 + stub_columns = self.directive.options.get('stub-columns', 0) 155 + header_rows = self.directive.options.get('header-rows', 0) 156 + 157 + table = nodes.table() 158 + tgroup = nodes.tgroup(cols=len(colwidths)) 159 + table += tgroup 160 + 161 + 162 + for colwidth in colwidths: 163 + colspec = nodes.colspec(colwidth=colwidth) 164 + # FIXME: It seems, that the stub method only works well in the 165 + # absence of rowspan (observed by the html buidler, the docutils-xml 166 + # build seems OK). This is not extraordinary, because there exists 167 + # no table directive (except *this* flat-table) which allows to 168 + # define coexistent of rowspan and stubs (there was no use-case 169 + # before flat-table). This should be reviewed (later). 170 + if stub_columns: 171 + colspec.attributes['stub'] = 1 172 + stub_columns -= 1 173 + tgroup += colspec 174 + stub_columns = self.directive.options.get('stub-columns', 0) 175 + 176 + if header_rows: 177 + thead = nodes.thead() 178 + tgroup += thead 179 + for row in self.rows[:header_rows]: 180 + thead += self.buildTableRowNode(row) 181 + 182 + tbody = nodes.tbody() 183 + tgroup += tbody 184 + 185 + for row in self.rows[header_rows:]: 186 + tbody += self.buildTableRowNode(row) 187 + return table 188 + 189 + def buildTableRowNode(self, row_data, classes=None): 190 + classes = [] if classes is None else classes 191 + row = nodes.row() 192 + for cell in row_data: 193 + if cell is None: 194 + continue 195 + cspan, rspan, cellElements = cell 196 + 197 + attributes = {"classes" : classes} 198 + if rspan: 199 + attributes['morerows'] = rspan 200 + if cspan: 201 + attributes['morecols'] = cspan 202 + entry = nodes.entry(**attributes) 203 + entry.extend(cellElements) 204 + row += entry 205 + return row 206 + 207 + def raiseError(self, msg): 208 + error = self.directive.state_machine.reporter.error( 209 + msg 210 + , nodes.literal_block(self.directive.block_text 211 + , self.directive.block_text) 212 + , line = self.directive.lineno ) 213 + raise SystemMessagePropagation(error) 214 + 215 + def parseFlatTableNode(self, node): 216 + u"""parses the node from a :py:class:`FlatTable` directive's body""" 217 + 218 + if len(node) != 1 or not isinstance(node[0], nodes.bullet_list): 219 + self.raiseError( 220 + 'Error parsing content block for the "%s" directive: ' 221 + 'exactly one bullet list expected.' % self.directive.name ) 222 + 223 + for rowNum, rowItem in enumerate(node[0]): 224 + row = self.parseRowItem(rowItem, rowNum) 225 + self.rows.append(row) 226 + self.roundOffTableDefinition() 227 + 228 + def roundOffTableDefinition(self): 229 + u"""Round off the table definition. 230 + 231 + This method rounds off the table definition in :py:member:`rows`. 232 + 233 + * This method inserts the needed ``None`` values for the missing cells 234 + arising from spanning cells over rows and/or columns. 235 + 236 + * recount the :py:member:`max_cols` 237 + 238 + * Autospan or fill (option ``fill-cells``) missing cells on the right 239 + side of the table-row 240 + """ 241 + 242 + y = 0 243 + while y < len(self.rows): 244 + x = 0 245 + 246 + while x < len(self.rows[y]): 247 + cell = self.rows[y][x] 248 + if cell is None: 249 + x += 1 250 + continue 251 + cspan, rspan = cell[:2] 252 + # handle colspan in current row 253 + for c in range(cspan): 254 + try: 255 + self.rows[y].insert(x+c+1, None) 256 + except: # pylint: disable=W0702 257 + # the user sets ambiguous rowspans 258 + pass # SDK.CONSOLE() 259 + # handle colspan in spanned rows 260 + for r in range(rspan): 261 + for c in range(cspan + 1): 262 + try: 263 + self.rows[y+r+1].insert(x+c, None) 264 + except: # pylint: disable=W0702 265 + # the user sets ambiguous rowspans 266 + pass # SDK.CONSOLE() 267 + x += 1 268 + y += 1 269 + 270 + # Insert the missing cells on the right side. For this, first 271 + # re-calculate the max columns. 272 + 273 + for row in self.rows: 274 + if self.max_cols < len(row): 275 + self.max_cols = len(row) 276 + 277 + # fill with empty cells or cellspan? 278 + 279 + fill_cells = False 280 + if 'fill-cells' in self.directive.options: 281 + fill_cells = True 282 + 283 + for row in self.rows: 284 + x = self.max_cols - len(row) 285 + if x and not fill_cells: 286 + if row[-1] is None: 287 + row.append( ( x - 1, 0, []) ) 288 + else: 289 + cspan, rspan, content = row[-1] 290 + row[-1] = (cspan + x, rspan, content) 291 + elif x and fill_cells: 292 + for i in range(x): 293 + row.append( (0, 0, nodes.comment()) ) 294 + 295 + def pprint(self): 296 + # for debugging 297 + retVal = "[ " 298 + for row in self.rows: 299 + retVal += "[ " 300 + for col in row: 301 + if col is None: 302 + retVal += ('%r' % col) 303 + retVal += "\n , " 304 + else: 305 + content = col[2][0].astext() 306 + if len (content) > 30: 307 + content = content[:30] + "..." 308 + retVal += ('(cspan=%s, rspan=%s, %r)' 309 + % (col[0], col[1], content)) 310 + retVal += "]\n , " 311 + retVal = retVal[:-2] 312 + retVal += "]\n , " 313 + retVal = retVal[:-2] 314 + return retVal + "]" 315 + 316 + def parseRowItem(self, rowItem, rowNum): 317 + row = [] 318 + childNo = 0 319 + error = False 320 + cell = None 321 + target = None 322 + 323 + for child in rowItem: 324 + if (isinstance(child , nodes.comment) 325 + or isinstance(child, nodes.system_message)): 326 + pass 327 + elif isinstance(child , nodes.target): 328 + target = child 329 + elif isinstance(child, nodes.bullet_list): 330 + childNo += 1 331 + cell = child 332 + else: 333 + error = True 334 + break 335 + 336 + if childNo != 1 or error: 337 + self.raiseError( 338 + 'Error parsing content block for the "%s" directive: ' 339 + 'two-level bullet list expected, but row %s does not ' 340 + 'contain a second-level bullet list.' 341 + % (self.directive.name, rowNum + 1)) 342 + 343 + for cellItem in cell: 344 + cspan, rspan, cellElements = self.parseCellItem(cellItem) 345 + if target is not None: 346 + cellElements.insert(0, target) 347 + row.append( (cspan, rspan, cellElements) ) 348 + return row 349 + 350 + def parseCellItem(self, cellItem): 351 + # search and remove cspan, rspan colspec from the first element in 352 + # this listItem (field). 353 + cspan = rspan = 0 354 + if not len(cellItem): 355 + return cspan, rspan, [] 356 + for elem in cellItem[0]: 357 + if isinstance(elem, colSpan): 358 + cspan = elem.get("span") 359 + elem.parent.remove(elem) 360 + continue 361 + if isinstance(elem, rowSpan): 362 + rspan = elem.get("span") 363 + elem.parent.remove(elem) 364 + continue 365 + return cspan, rspan, cellItem[:]
+19
Documentation/sphinx/tmplcvt
··· 1 + #!/bin/bash 2 + # 3 + # Convert a template file into something like RST 4 + # 5 + # fix <function> 6 + # feed to pandoc 7 + # fix \_ 8 + # title line? 9 + # 10 + 11 + in=$1 12 + rst=$2 13 + tmp=$rst.tmp 14 + 15 + cp $in $tmp 16 + sed --in-place -f convert_template.sed $tmp 17 + pandoc -s -S -f docbook -t rst -o $rst $tmp 18 + sed --in-place -f post_convert.sed $rst 19 + rm $tmp
+3 -3
Documentation/sync_file.txt
··· 6 6 7 7 This document serves as a guide for device drivers writers on what the 8 8 sync_file API is, and how drivers can support it. Sync file is the carrier of 9 - the fences(struct fence) that needs to synchronized between drivers or across 10 - process boundaries. 9 + the fences(struct fence) that are needed to synchronize between drivers or 10 + across process boundaries. 11 11 12 12 The sync_file API is meant to be used to send and receive fence information 13 13 to/from userspace. It enables userspace to do explicit fencing, where instead ··· 32 32 Sync files can go either to or from userspace. When a sync_file is sent from 33 33 the driver to userspace we call the fences it contains 'out-fences'. They are 34 34 related to a buffer that the driver is processing or is going to process, so 35 - the driver an create out-fence to be able to notify, through fence_signal(), 35 + the driver creates an out-fence to be able to notify, through fence_signal(), 36 36 when it has finished using (or processing) that buffer. Out-fences are fences 37 37 that the driver creates. 38 38
+1
Documentation/sysctl/vm.txt
··· 61 61 - swappiness 62 62 - user_reserve_kbytes 63 63 - vfs_cache_pressure 64 + - watermark_scale_factor 64 65 - zone_reclaim_mode 65 66 66 67 ==============================================================
+1 -1
Documentation/thermal/intel_powerclamp.txt
··· 121 121 cannot be based on the past or current input. Therefore, the 122 122 intel_powerclamp driver attempts to enforce the desired idle time 123 123 instantly as given input (target idle ratio). After injection, 124 - powerclamp moniors the actual idle for a given time window and adjust 124 + powerclamp monitors the actual idle for a given time window and adjust 125 125 the next injection accordingly to avoid over/under correction. 126 126 127 127 When used in a causal control system, such as a temperature control,
+1 -1
Documentation/usb/gadget_multi.txt
··· 36 36 37 37 ** Windows host drivers 38 38 39 - For the gadget two work under Windows two conditions have to be met: 39 + For the gadget to work under Windows two conditions have to be met: 40 40 41 41 *** Detecting as composite gadget 42 42
+1 -1
Documentation/workqueue.txt
··· 169 169 WQ_UNBOUND 170 170 171 171 Work items queued to an unbound wq are served by the special 172 - woker-pools which host workers which are not bound to any 172 + worker-pools which host workers which are not bound to any 173 173 specific CPU. This makes the wq behave as a simple execution 174 174 context provider without concurrency management. The unbound 175 175 worker-pools try to start execution of work items as soon as
+341 -222
Documentation/zh_CN/CodingStyle
··· 24 24 25 25 Linux内核代码风格 26 26 27 - 这是一个简短的文档,描述了linux内核的首选代码风格。代码风格是因人而异的,而且我 28 - 不愿意把我的观点强加给任何人,不过这里所讲述的是我必须要维护的代码所遵守的风格, 29 - 并且我也希望绝大多数其他代码也能遵守这个风格。请在写代码时至少考虑一下本文所述的 30 - 风格。 27 + 这是一个简短的文档,描述了 linux 内核的首选代码风格。代码风格是因人而异的,而且我 28 + 不愿意把自己的观点强加给任何人,但这就像我去做任何事情都必须遵循的原则那样,我也 29 + 希望在绝大多数事上保持这种的态度。请(在写代码时)至少考虑一下这里的代码风格。 31 30 32 - 首先,我建议你打印一份GNU代码规范,然后不要读它。烧了它,这是一个具有重大象征性 33 - 意义的动作。 31 + 首先,我建议你打印一份 GNU 代码规范,然后不要读。烧了它,这是一个具有重大象征性意义 32 + 的动作。 34 33 35 34 不管怎样,现在我们开始: 36 35 37 36 38 - 第一章:缩进 37 + 第一章:缩进 39 38 40 - 制表符是8个字符,所以缩进也是8个字符。有些异端运动试图将缩进变为4(乃至2)个字符 41 - 深,这几乎相当于尝试将圆周率的值定义为3。 39 + 制表符是 8 个字符,所以缩进也是 8 个字符。有些异端运动试图将缩进变为 4(甚至 2!) 40 + 个字符深,这几乎相当于尝试将圆周率的值定义为 3。 42 41 43 42 理由:缩进的全部意义就在于清楚的定义一个控制块起止于何处。尤其是当你盯着你的屏幕 44 - 连续看了20小时之后,你将会发现大一点的缩进会使你更容易分辨缩进。 43 + 连续看了 20 小时之后,你将会发现大一点的缩进会使你更容易分辨缩进。 45 44 46 - 现在,有些人会抱怨8个字符的缩进会使代码向右边移动的太远,在80个字符的终端屏幕上 47 - 就很难读这样的代码。这个问题的答案是,如果你需要3级以上的缩进,不管用何种方式你 45 + 现在,有些人会抱怨 8 个字符的缩进会使代码向右边移动的太远,在 80 个字符的终端屏幕上 46 + 就很难读这样的代码。这个问题的答案是,如果你需要 3 级以上的缩进,不管用何种方式你 48 47 的代码已经有问题了,应该修正你的程序。 49 48 50 - 简而言之,8个字符的缩进可以让代码更容易阅读,还有一个好处是当你的函数嵌套太深的 49 + 简而言之,8 个字符的缩进可以让代码更容易阅读,还有一个好处是当你的函数嵌套太深的 51 50 时候可以给你警告。留心这个警告。 52 51 53 - 在switch语句中消除多级缩进的首选的方式是让“switch”和从属于它的“case”标签对齐于同 54 - 一列,而不要“两次缩进”“case”标签。比如: 52 + 在 switch 语句中消除多级缩进的首选的方式是让 “switch” 和从属于它的 “case” 标签 53 + 对齐于同一列,而不要 “两次缩进” “case” 标签。比如: 55 54 56 55 switch (suffix) { 57 56 case 'G': ··· 69 70 break; 70 71 } 71 72 72 - 73 73 不要把多个语句放在一行里,除非你有什么东西要隐藏: 74 74 75 75 if (condition) do_this; ··· 77 79 也不要在一行里放多个赋值语句。内核代码风格超级简单。就是避免可能导致别人误读的表 78 80 达式。 79 81 80 - 除了注释、文档和Kconfig之外,不要使用空格来缩进,前面的例子是例外,是有意为之。 82 + 除了注释、文档和 Kconfig 之外,不要使用空格来缩进,前面的例子是例外,是有意为之。 81 83 82 84 选用一个好的编辑器,不要在行尾留空格。 83 85 ··· 86 88 87 89 代码风格的意义就在于使用平常使用的工具来维持代码的可读性和可维护性。 88 90 89 - 每一行的长度的限制是80列,我们强烈建议您遵守这个惯例。 91 + 每一行的长度的限制是 80 列,我们强烈建议您遵守这个惯例。 90 92 91 - 长于80列的语句要打散成有意义的片段。每个片段要明显短于原来的语句,而且放置的位置 92 - 也明显的靠右。同样的规则也适用于有很长参数列表的函数头。长字符串也要打散成较短的 93 - 字符串。唯一的例外是超过80列可以大幅度提高可读性并且不会隐藏信息的情况。 94 - 95 - void fun(int a, int b, int c) 96 - { 97 - if (condition) 98 - printk(KERN_WARNING "Warning this is a long printk with " 99 - "3 parameters a: %u b: %u " 100 - "c: %u \n", a, b, c); 101 - else 102 - next_statement; 103 - } 93 + 长于 80 列的语句要打散成有意义的片段。除非超过 80 列能显著增加可读性,并且不会隐藏 94 + 信息。子片段要明显短于母片段,并明显靠右。这同样适用于有着很长参数列表的函数头。 95 + 然而,绝对不要打散对用户可见的字符串,例如 printk 信息,因为这将导致无法 grep 这些 96 + 信息。 104 97 105 98 第三章:大括号和空格的放置 106 99 107 100 C语言风格中另外一个常见问题是大括号的放置。和缩进大小不同,选择或弃用某种放置策 108 - 略并没有多少技术上的原因,不过首选的方式,就像Kernighan和Ritchie展示给我们的,是 109 - 把起始大括号放在行尾,而把结束大括号放在行首,所以: 101 + 略并没有多少技术上的原因,不过首选的方式,就像 Kernighan 和 Ritchie 展示给我们的, 102 + 是把起始大括号放在行尾,而把结束大括号放在行首,所以: 110 103 111 104 if (x is true) { 112 105 we do y ··· 123 134 body of function 124 135 } 125 136 126 - 全世界的异端可能会抱怨这个不一致性是……呃……不一致的,不过所有思维健全的人都知道( 127 - a)K&R是_正确的_,并且(b)K&R是正确的。此外,不管怎样函数都是特殊的(在C语言中 128 - ,函数是不能嵌套的)。 137 + 全世界的异端可能会抱怨这个不一致性是……呃……不一致的,不过所有思维健全的人都知道 138 + (a) K&R 是 _正确的_,并且 (b) K&R 是正确的。此外,不管怎样函数都是特殊的(C 139 + 函数是不能嵌套的)。 129 140 130 - 注意结束大括号独自占据一行,除非它后面跟着同一个语句的剩余部分,也就是do语句中的 131 - “while”或者if语句中的“else”,像这样: 141 + 注意结束大括号独自占据一行,除非它后面跟着同一个语句的剩余部分,也就是 do 语句中的 142 + “while” 或者 if 语句中的 “else”,像这样: 132 143 133 144 do { 134 145 body of do-loop ··· 147 158 理由:K&R。 148 159 149 160 也请注意这种大括号的放置方式也能使空(或者差不多空的)行的数量最小化,同时不失可 150 - 读性。因此,由于你的屏幕上的新行是不可再生资源(想想25行的终端屏幕),你将会有更 161 + 读性。因此,由于你的屏幕上的新行是不可再生资源(想想 25 行的终端屏幕),你将会有更 151 162 多的空行来放置注释。 152 163 153 164 当只有一个单独的语句的时候,不用加不必要的大括号。 154 165 155 - if (condition) 156 - action(); 166 + if (condition) 167 + action(); 157 168 158 - 这点不适用于本身为某个条件语句的一个分支的单独语句。这时需要在两个分支里都使用大 159 - 括号。 169 + 160 170 161 - if (condition) { 162 - do_this(); 163 - do_that(); 164 - } else { 165 - otherwise(); 166 - } 171 + if (condition) 172 + do_this(); 173 + else 174 + do_that(); 175 + 176 + 这并不适用于只有一个条件分支是单语句的情况;这时所有分支都要使用大括号: 177 + 178 + if (condition) { 179 + do_this(); 180 + do_that(); 181 + } else { 182 + otherwise(); 183 + } 167 184 168 185 3.1:空格 169 186 170 - Linux内核的空格使用方式(主要)取决于它是用于函数还是关键字。(大多数)关键字后 171 - 要加一个空格。值得注意的例外是sizeof、typeof、alignof和__attribute__,这些关键字 172 - 某些程度上看起来更像函数(它们在Linux里也常常伴随小括号而使用,尽管在C语言里这样 173 - 的小括号不是必需的,就像“struct fileinfo info”声明过后的“sizeof info”)。 187 + Linux 内核的空格使用方式(主要)取决于它是用于函数还是关键字。(大多数)关键字后 188 + 要加一个空格。值得注意的例外是 sizeof、typeof、alignof 和 __attribute__,这些 189 + 关键字某些程度上看起来更像函数(它们在 Linux 里也常常伴随小括号而使用,尽管在 C 里 190 + 这样的小括号不是必需的,就像 “struct fileinfo info” 声明过后的 “sizeof info”)。 174 191 175 192 所以在这些关键字之后放一个空格: 193 + 176 194 if, switch, case, for, do, while 177 - 但是不要在sizeof、typeof、alignof或者__attribute__这些关键字之后放空格。例如, 195 + 196 + 但是不要在 sizeof、typeof、alignof 或者 __attribute__ 这些关键字之后放空格。例如, 197 + 178 198 s = sizeof(struct file); 179 199 180 200 不要在小括号里的表达式两侧加空格。这是一个反例: 181 201 182 202 s = sizeof( struct file ); 183 203 184 - 当声明指针类型或者返回指针类型的函数时,“*”的首选使用方式是使之靠近变量名或者函 204 + 当声明指针类型或者返回指针类型的函数时,“*” 的首选使用方式是使之靠近变量名或者函 185 205 数名,而不是靠近类型名。例子: 186 206 187 207 char *linux_banner; ··· 202 204 = + - < > * / % | & ^ <= >= == != ? : 203 205 204 206 但是一元操作符后不要加空格: 207 + 205 208 & * + - ~ ! sizeof typeof alignof __attribute__ defined 206 209 207 210 后缀自加和自减一元操作符前不加空格: 211 + 208 212 ++ -- 209 213 210 214 前缀自加和自减一元操作符后不加空格: 215 + 211 216 ++ -- 212 217 213 - “.”和“->”结构体成员操作符前后不加空格。 218 + ‘.’ 和 “->” 结构体成员操作符前后不加空格。 214 219 215 220 不要在行尾留空白。有些可以自动缩进的编辑器会在新行的行首加入适量的空白,然后你 216 221 就可以直接在那一行输入代码。不过假如你最后没有在那一行输入代码,有些编辑器就不 ··· 226 225 227 226 第四章:命名 228 227 229 - C是一个简朴的语言,你的命名也应该这样。和Modula-2和Pascal程序员不同,C程序员不使 230 - 用类似ThisVariableIsATemporaryCounter这样华丽的名字。C程序员会称那个变量为“tmp” 231 - ,这样写起来会更容易,而且至少不会令其难于理解。 228 + C是一个简朴的语言,你的命名也应该这样。和 Modula-2 和 Pascal 程序员不同,C 程序员 229 + 不使用类似 ThisVariableIsATemporaryCounter 这样华丽的名字。C 程序员会称那个变量 230 + 为 “tmp”,这样写起来会更容易,而且至少不会令其难于理解。 232 231 233 232 不过,虽然混用大小写的名字是不提倡使用的,但是全局变量还是需要一个具描述性的名字 234 - 。称一个全局函数为“foo”是一个难以饶恕的错误。 233 + 。称一个全局函数为 “foo” 是一个难以饶恕的错误。 235 234 236 235 全局变量(只有当你真正需要它们的时候再用它)需要有一个具描述性的名字,就像全局函 237 - 数。如果你有一个可以计算活动用户数量的函数,你应该叫它“count_active_users()”或者 238 - 类似的名字,你不应该叫它“cntuser()”。 236 + 数。如果你有一个可以计算活动用户数量的函数,你应该叫它 “count_active_users()” 237 + 或者类似的名字,你不应该叫它 “cntuser()”。 239 238 240 239 在函数名中包含函数类型(所谓的匈牙利命名法)是脑子出了问题——编译器知道那些类型而 241 240 且能够检查那些类型,这样做只能把程序员弄糊涂了。难怪微软总是制造出有问题的程序。 242 241 243 242 本地变量名应该简短,而且能够表达相关的含义。如果你有一些随机的整数型的循环计数器 244 - ,它应该被称为“i”。叫它“loop_counter”并无益处,如果它没有被误解的可能的话。类似 245 - 的,“tmp”可以用来称呼任意类型的临时变量。 243 + ,它应该被称为 “i”。叫它 “loop_counter” 并无益处,如果它没有被误解的可能的话。 244 + 类似的,“tmp” 可以用来称呼任意类型的临时变量。 246 245 247 246 如果你怕混淆了你的本地变量名,你就遇到另一个问题了,叫做函数增长荷尔蒙失衡综合症 248 247 。请看第六章(函数)。 ··· 250 249 251 250 第五章:Typedef 252 251 253 - 不要使用类似“vps_t”之类的东西。 252 + 不要使用类似 “vps_t” 之类的东西。 254 253 255 - 对结构体和指针使用typedef是一个错误。当你在代码里看到: 254 + 对结构体和指针使用 typedef 是一个错误。当你在代码里看到: 256 255 257 256 vps_t a; 258 257 ··· 262 261 263 262 struct virtual_container *a; 264 263 265 - 你就知道“a”是什么了。 264 + 你就知道 “a” 是什么了。 266 265 267 - 很多人认为typedef“能提高可读性”。实际不是这样的。它们只在下列情况下有用: 266 + 很多人认为 typedef “能提高可读性”。实际不是这样的。它们只在下列情况下有用: 268 267 269 - (a) 完全不透明的对象(这种情况下要主动使用typedef来隐藏这个对象实际上是什么)。 268 + (a) 完全不透明的对象(这种情况下要主动使用 typedef 来隐藏这个对象实际上是什么)。 270 269 271 - 例如:“pte_t”等不透明对象,你只能用合适的访问函数来访问它们。 270 + 例如:“pte_t” 等不透明对象,你只能用合适的访问函数来访问它们。 272 271 273 - 注意!不透明性和“访问函数”本身是不好的。我们使用pte_t等类型的原因在于真的是 272 + 注意!不透明性和“访问函数”本身是不好的。我们使用 pte_t 等类型的原因在于真的是 274 273 完全没有任何共用的可访问信息。 275 274 276 - (b) 清楚的整数类型,如此,这层抽象就可以帮助消除到底是“int”还是“long”的混淆。 275 + (b) 清楚的整数类型,如此,这层抽象就可以帮助消除到底是 “int” 还是 “long” 的混淆。 277 276 278 - u8/u16/u32是完全没有问题的typedef,不过它们更符合类别(d)而不是这里。 277 + u8/u16/u32 是完全没有问题的 typedef,不过它们更符合类别 (d) 而不是这里。 279 278 280 - 再次注意!要这样做,必须事出有因。如果某个变量是“unsigned long“,那么没有必要 279 + 再次注意!要这样做,必须事出有因。如果某个变量是 “unsigned long“,那么没有必要 281 280 282 281 typedef unsigned long myflags_t; 283 282 284 - 不过如果有一个明确的原因,比如它在某种情况下可能会是一个“unsigned int”而在 285 - 其他情况下可能为“unsigned long”,那么就不要犹豫,请务必使用typedef。 283 + 不过如果有一个明确的原因,比如它在某种情况下可能会是一个 “unsigned int” 而在 284 + 其他情况下可能为 “unsigned long”,那么就不要犹豫,请务必使用 typedef。 286 285 287 286 (c) 当你使用sparse按字面的创建一个新类型来做类型检查的时候。 288 287 289 288 (d) 和标准C99类型相同的类型,在某些例外的情况下。 290 289 291 - 虽然让眼睛和脑筋来适应新的标准类型比如“uint32_t”不需要花很多时间,可是有些 290 + 虽然让眼睛和脑筋来适应新的标准类型比如 “uint32_t” 不需要花很多时间,可是有些 292 291 人仍然拒绝使用它们。 293 292 294 - 因此,Linux特有的等同于标准类型的“u8/u16/u32/u64”类型和它们的有符号类型是被 293 + 因此,Linux 特有的等同于标准类型的 “u8/u16/u32/u64” 类型和它们的有符号类型是被 295 294 允许的——尽管在你自己的新代码中,它们不是强制要求要使用的。 296 295 297 296 当编辑已经使用了某个类型集的已有代码时,你应该遵循那些代码中已经做出的选择。 298 297 299 298 (e) 可以在用户空间安全使用的类型。 300 299 301 - 在某些用户空间可见的结构体里,我们不能要求C99类型而且不能用上面提到的“u32” 302 - 类型。因此,我们在与用户空间共享的所有结构体中使用__u32和类似的类型。 300 + 在某些用户空间可见的结构体里,我们不能要求C99类型而且不能用上面提到的 “u32” 301 + 类型。因此,我们在与用户空间共享的所有结构体中使用 __u32 和类似的类型。 303 302 304 - 可能还有其他的情况,不过基本的规则是永远不要使用typedef,除非你可以明确的应用上 303 + 可能还有其他的情况,不过基本的规则是永远不要使用 typedef,除非你可以明确的应用上 305 304 述某个规则中的一个。 306 305 307 306 总的来说,如果一个指针或者一个结构体里的元素可以合理的被直接访问到,那么它们就不 308 - 应该是一个typedef。 307 + 应该是一个 typedef。 309 308 310 309 311 310 第六章:函数 312 311 313 312 函数应该简短而漂亮,并且只完成一件事情。函数应该可以一屏或者两屏显示完(我们都知 314 - 道ISO/ANSI屏幕大小是80x24),只做一件事情,而且把它做好。 313 + 道 ISO/ANSI 屏幕大小是 80x24),只做一件事情,而且把它做好。 315 314 316 315 一个函数的最大长度是和该函数的复杂度和缩进级数成反比的。所以,如果你有一个理论上 317 - 很简单的只有一个很长(但是简单)的case语句的函数,而且你需要在每个case里做很多很 318 - 小的事情,这样的函数尽管很长,但也是可以的。 316 + 很简单的只有一个很长(但是简单)的 case 语句的函数,而且你需要在每个 case 里做 317 + 很多很小的事情,这样的函数尽管很长,但也是可以的。 319 318 320 319 不过,如果你有一个复杂的函数,而且你怀疑一个天分不是很高的高中一年级学生可能甚至 321 320 搞不清楚这个函数的目的,你应该严格的遵守前面提到的长度限制。使用辅助函数,并为之 322 321 取个具描述性的名字(如果你觉得它们的性能很重要的话,可以让编译器内联它们,这样的 323 322 效果往往会比你写一个复杂函数的效果要好。) 324 323 325 - 函数的另外一个衡量标准是本地变量的数量。此数量不应超过5-10个,否则你的函数就有 324 + 函数的另外一个衡量标准是本地变量的数量。此数量不应超过 5-10 个,否则你的函数就有 326 325 问题了。重新考虑一下你的函数,把它分拆成更小的函数。人的大脑一般可以轻松的同时跟 327 - 踪7个不同的事物,如果再增多的话,就会糊涂了。即便你聪颖过人,你也可能会记不清你2 328 - 个星期前做过的事情。 326 + 踪 7 个不同的事物,如果再增多的话,就会糊涂了。即便你聪颖过人,你也可能会记不清你 327 + 2 个星期前做过的事情。 329 328 330 - 在源文件里,使用空行隔开不同的函数。如果该函数需要被导出,它的EXPORT*宏应该紧贴 329 + 在源文件里,使用空行隔开不同的函数。如果该函数需要被导出,它的 EXPORT* 宏应该紧贴 331 330 在它的结束大括号之下。比如: 332 331 333 - int system_is_up(void) 334 - { 335 - return system_state == SYSTEM_RUNNING; 336 - } 337 - EXPORT_SYMBOL(system_is_up); 332 + int system_is_up(void) 333 + { 334 + return system_state == SYSTEM_RUNNING; 335 + } 336 + EXPORT_SYMBOL(system_is_up); 338 337 339 - 在函数原型中,包含函数名和它们的数据类型。虽然C语言里没有这样的要求,在Linux里这 338 + 在函数原型中,包含函数名和它们的数据类型。虽然C语言里没有这样的要求,在 Linux 里这 340 339 是提倡的做法,因为这样可以很简单的给读者提供更多的有价值的信息。 341 340 342 341 343 342 第七章:集中的函数退出途径 344 343 345 - 虽然被某些人声称已经过时,但是goto语句的等价物还是经常被编译器所使用,具体形式是 344 + 虽然被某些人声称已经过时,但是 goto 语句的等价物还是经常被编译器所使用,具体形式是 346 345 无条件跳转指令。 347 346 348 - 当一个函数从多个位置退出并且需要做一些通用的清理工作的时候,goto的好处就显现出来 349 - 了。 347 + 当一个函数从多个位置退出,并且需要做一些类似清理的常见操作时,goto 语句就很方便了。 348 + 如果并不需要清理操作,那么直接 return 即可。 350 349 351 350 理由是: 352 351 ··· 355 354 - 可以避免由于修改时忘记更新某个单独的退出点而导致的错误 356 355 - 减轻了编译器的工作,无需删除冗余代码;) 357 356 358 - int fun(int a) 359 - { 360 - int result = 0; 361 - char *buffer = kmalloc(SIZE); 357 + int fun(int a) 358 + { 359 + int result = 0; 360 + char *buffer; 362 361 363 - if (buffer == NULL) 364 - return -ENOMEM; 362 + buffer = kmalloc(SIZE, GFP_KERNEL); 363 + if (!buffer) 364 + return -ENOMEM; 365 365 366 - if (condition1) { 367 - while (loop1) { 368 - ... 366 + if (condition1) { 367 + while (loop1) { 368 + ... 369 + } 370 + result = 1; 371 + goto out_buffer; 369 372 } 370 - result = 1; 371 - goto out; 373 + ... 374 + out_buffer: 375 + kfree(buffer); 376 + return result; 372 377 } 373 - ... 374 - out: 375 - kfree(buffer); 376 - return result; 377 - } 378 + 379 + 一个需要注意的常见错误是“一个 err 错误”,就像这样: 380 + 381 + err: 382 + kfree(foo->bar); 383 + kfree(foo); 384 + return ret; 385 + 386 + 这段代码的错误是,在某些退出路径上 “foo” 是 NULL。通常情况下,通过把它分离成两个 387 + 错误标签 “err_bar:” 和 “err_foo:” 来修复这个错误。 378 388 379 389 第八章:注释 380 390 ··· 398 386 加太多。你应该做的,是把注释放在函数的头部,告诉人们它做了什么,也可以加上它做这 399 387 些事情的原因。 400 388 401 - 当注释内核API函数时,请使用kernel-doc格式。请看 402 - Documentation/kernel-doc-nano-HOWTO.txt和scripts/kernel-doc以获得详细信息。 389 + 当注释内核API函数时,请使用 kernel-doc 格式。请看 390 + Documentation/kernel-documentation.rst和scripts/kernel-doc 以获得详细信息。 403 391 404 - Linux的注释风格是C89“/* ... */”风格。不要使用C99风格“// ...”注释。 392 + Linux的注释风格是 C89 “/* ... */” 风格。不要使用 C99 风格 “// ...” 注释。 405 393 406 394 长(多行)的首选注释风格是: 407 395 ··· 414 402 * with beginning and ending almost-blank lines. 415 403 */ 416 404 405 + 对于在 net/ 和 drivers/net/ 的文件,首选的长(多行)注释风格有些不同。 406 + 407 + /* The preferred comment style for files in net/ and drivers/net 408 + * looks like this. 409 + * 410 + * It is nearly the same as the generally preferred comment style, 411 + * but there is no initial almost-blank line. 412 + */ 413 + 417 414 注释数据也是很重要的,不管是基本类型还是衍生类型。为了方便实现这一点,每一行应只 418 415 声明一个数据(不要使用逗号来一次声明多个数据)。这样你就有空间来为每个数据写一段 419 416 小注释来解释它们的用途了。 ··· 430 409 431 410 第九章:你已经把事情弄糟了 432 411 433 - 这没什么,我们都是这样。可能你的使用了很长时间Unix的朋友已经告诉你“GNU emacs”能 434 - 自动帮你格式化C源代码,而且你也注意到了,确实是这样,不过它所使用的默认值和我们 435 - 想要的相去甚远(实际上,甚至比随机打的还要差——无数个猴子在GNU emacs里打字永远不 436 - 会创造出一个好程序)(译注:请参考Infinite Monkey Theorem) 412 + 这没什么,我们都是这样。可能你的使用了很长时间 Unix 的朋友已经告诉你 “GNU emacs” 能 413 + 自动帮你格式化 C 源代码,而且你也注意到了,确实是这样,不过它所使用的默认值和我们 414 + 想要的相去甚远(实际上,甚至比随机打的还要差——无数个猴子在 GNU emacs 里打字永远不 415 + 会创造出一个好程序)(译注:请参考 Infinite Monkey Theorem) 437 416 438 - 所以你要么放弃GNU emacs,要么改变它让它使用更合理的设定。要采用后一个方案,你可 439 - 以把下面这段粘贴到你的.emacs文件里。 417 + 所以你要么放弃 GNU emacs,要么改变它让它使用更合理的设定。要采用后一个方案,你可 418 + 以把下面这段粘贴到你的 .emacs 文件里。 440 419 441 - (defun linux-c-mode () 442 - "C mode with adjusted defaults for use with the Linux kernel." 443 - (interactive) 444 - (c-mode) 445 - (c-set-style "K&R") 446 - (setq tab-width 8) 447 - (setq indent-tabs-mode t) 448 - (setq c-basic-offset 8)) 420 + (defun c-lineup-arglist-tabs-only (ignored) 421 + "Line up argument lists by tabs, not spaces" 422 + (let* ((anchor (c-langelem-pos c-syntactic-element)) 423 + (column (c-langelem-2nd-pos c-syntactic-element)) 424 + (offset (- (1+ column) anchor)) 425 + (steps (floor offset c-basic-offset))) 426 + (* (max steps 1) 427 + c-basic-offset))) 449 428 450 - 这样就定义了M-x linux-c-mode命令。当你hack一个模块的时候,如果你把字符串 451 - -*- linux-c -*-放在头两行的某个位置,这个模式将会被自动调用。如果你希望在你修改 452 - /usr/src/linux里的文件时魔术般自动打开linux-c-mode的话,你也可能需要添加 429 + (add-hook 'c-mode-common-hook 430 + (lambda () 431 + ;; Add kernel style 432 + (c-add-style 433 + "linux-tabs-only" 434 + '("linux" (c-offsets-alist 435 + (arglist-cont-nonempty 436 + c-lineup-gcc-asm-reg 437 + c-lineup-arglist-tabs-only)))))) 453 438 454 - (setq auto-mode-alist (cons '("/usr/src/linux.*/.*\\.[ch]$" . linux-c-mode) 455 - auto-mode-alist)) 439 + (add-hook 'c-mode-hook 440 + (lambda () 441 + (let ((filename (buffer-file-name))) 442 + ;; Enable kernel mode for the appropriate files 443 + (when (and filename 444 + (string-match (expand-file-name "~/src/linux-trees") 445 + filename)) 446 + (setq indent-tabs-mode t) 447 + (setq show-trailing-whitespace t) 448 + (c-set-style "linux-tabs-only"))))) 456 449 457 - 到你的.emacs文件里。 450 + 这会让 emacs 在 ~/src/linux-trees 目录下的 C 源文件获得更好的内核代码风格。 458 451 459 - 不过就算你尝试让emacs正确的格式化代码失败了,也并不意味着你失去了一切:还可以用“ 460 - indent”。 452 + 不过就算你尝试让 emacs 正确的格式化代码失败了,也并不意味着你失去了一切:还可以用 453 + “indent”。 461 454 462 - 不过,GNU indent也有和GNU emacs一样有问题的设定,所以你需要给它一些命令选项。不 463 - 过,这还不算太糟糕,因为就算是GNU indent的作者也认同K&R的权威性(GNU的人并不是坏 464 - 人,他们只是在这个问题上被严重的误导了),所以你只要给indent指定选项“-kr -i8” 465 - (代表“K&R,8个字符缩进”),或者使用“scripts/Lindent”,这样就可以以最时髦的方式 455 + 不过,GNU indent 也有和 GNU emacs 一样有问题的设定,所以你需要给它一些命令选项。不 456 + 过,这还不算太糟糕,因为就算是 GNU indent 的作者也认同 K&R 的权威性(GNU 的人并不是 457 + 坏人,他们只是在这个问题上被严重的误导了),所以你只要给 indent 指定选项 “-kr -i8” 458 + (代表 “K&R,8 个字符缩进”),或者使用 “scripts/Lindent”,这样就可以以最时髦的方式 466 459 缩进源代码。 467 460 468 - “indent”有很多选项,特别是重新格式化注释的时候,你可能需要看一下它的手册页。不过 469 - 记住:“indent”不能修正坏的编程习惯。 461 + “indent” 有很多选项,特别是重新格式化注释的时候,你可能需要看一下它的手册页。不过 462 + 记住:“indent” 不能修正坏的编程习惯。 470 463 471 464 472 - 第十章:Kconfig配置文件 465 + 第十章:Kconfig 配置文件 473 466 474 - 对于遍布源码树的所有Kconfig*配置文件来说,它们缩进方式与C代码相比有所不同。紧挨 475 - 在“config”定义下面的行缩进一个制表符,帮助信息则再多缩进2个空格。比如: 467 + 对于遍布源码树的所有 Kconfig* 配置文件来说,它们缩进方式与 C 代码相比有所不同。紧挨 468 + 在 “config” 定义下面的行缩进一个制表符,帮助信息则再多缩进 2 个空格。比如: 476 469 477 470 config AUDIT 478 471 bool "Auditing support" ··· 505 470 depends on ADFS_FS 506 471 ... 507 472 508 - 要查看配置文件的完整文档,请看Documentation/kbuild/kconfig-language.txt。 473 + 要查看配置文件的完整文档,请看 Documentation/kbuild/kconfig-language.txt。 509 474 510 475 511 476 第十一章:数据结构 ··· 524 489 很多数据结构实际上有2级引用计数,它们通常有不同“类”的用户。子类计数器统计子类用 525 490 户的数量,每当子类计数器减至零时,全局计数器减一。 526 491 527 - 这种“多级引用计数”的例子可以在内存管理(“struct mm_struct”:mm_users和mm_count) 492 + 这种“多级引用计数”的例子可以在内存管理(“struct mm_struct”:mm_users 和 mm_count) 528 493 和文件系统(“struct super_block”:s_count和s_active)中找到。 529 494 530 495 记住:如果另一个执行线索可以找到你的数据结构,但是这个数据结构没有引用计数器,这 531 - 里几乎肯定是一个bug。 496 + 里几乎肯定是一个 bug。 532 497 533 498 534 499 第十二章:宏,枚举和RTL ··· 543 508 544 509 一般的,如果能写成内联函数就不要写成像函数的宏。 545 510 546 - 含有多个语句的宏应该被包含在一个do-while代码块里: 511 + 含有多个语句的宏应该被包含在一个 do-while 代码块里: 547 512 548 - #define macrofun(a, b, c) \ 549 - do { \ 550 - if (a == 5) \ 551 - do_this(b, c); \ 552 - } while (0) 513 + #define macrofun(a, b, c) \ 514 + do { \ 515 + if (a == 5) \ 516 + do_this(b, c); \ 517 + } while (0) 553 518 554 519 使用宏的时候应避免的事情: 555 520 556 521 1) 影响控制流程的宏: 557 522 558 - #define FOO(x) \ 559 - do { \ 560 - if (blah(x) < 0) \ 561 - return -EBUGGERED; \ 562 - } while(0) 523 + #define FOO(x) \ 524 + do { \ 525 + if (blah(x) < 0) \ 526 + return -EBUGGERED; \ 527 + } while (0) 563 528 564 529 非常不好。它看起来像一个函数,不过却能导致“调用”它的函数退出;不要打乱读者大脑里 565 530 的语法分析器。 566 531 567 532 2) 依赖于一个固定名字的本地变量的宏: 568 533 569 - #define FOO(val) bar(index, val) 534 + #define FOO(val) bar(index, val) 570 535 571 536 可能看起来像是个不错的东西,不过它非常容易把读代码的人搞糊涂,而且容易导致看起来 572 537 不相关的改动带来错误。 573 538 574 - 3) 作为左值的带参数的宏: FOO(x) = y;如果有人把FOO变成一个内联函数的话,这种用 539 + 3) 作为左值的带参数的宏: FOO(x) = y;如果有人把 FOO 变成一个内联函数的话,这种用 575 540 法就会出错了。 576 541 577 542 4) 忘记了优先级:使用表达式定义常量的宏必须将表达式置于一对小括号之内。带参数的 578 543 宏也要注意此类问题。 579 544 580 - #define CONSTANT 0x4000 581 - #define CONSTEXP (CONSTANT | 3) 545 + #define CONSTANT 0x4000 546 + #define CONSTEXP (CONSTANT | 3) 582 547 583 - cpp手册对宏的讲解很详细。Gcc internals手册也详细讲解了RTL(译注:register 548 + 5) 在宏里定义类似函数的本地变量时命名冲突: 549 + 550 + #define FOO(x) \ 551 + ({ \ 552 + typeof(x) ret; \ 553 + ret = calc_ret(x); \ 554 + (ret); \ 555 + }) 556 + 557 + ret 是本地变量的通用名字 - __foo_ret 更不容易与一个已存在的变量冲突。 558 + 559 + cpp 手册对宏的讲解很详细。gcc internals 手册也详细讲解了 RTL(译注:register 584 560 transfer language),内核里的汇编语言经常用到它。 585 561 586 562 587 563 第十三章:打印内核消息 588 564 589 565 内核开发者应该是受过良好教育的。请一定注意内核信息的拼写,以给人以好的印象。不要 590 - 用不规范的单词比如“dont”,而要用“do not”或者“don't”。保证这些信息简单、明了、无 591 - 歧义。 566 + 用不规范的单词比如 “dont”,而要用 “do not”或者 “don't”。保证这些信息简单、明了、 567 + 无歧义。 592 568 593 569 内核信息不必以句号(译注:英文句号,即点)结束。 594 570 595 - 在小括号里打印数字(%d)没有任何价值,应该避免这样做。 571 + 在小括号里打印数字 (%d) 没有任何价值,应该避免这样做。 596 572 597 - <linux/device.h>里有一些驱动模型诊断宏,你应该使用它们,以确保信息对应于正确的 598 - 设备和驱动,并且被标记了正确的消息级别。这些宏有:dev_err(), dev_warn(), 599 - dev_info()等等。对于那些不和某个特定设备相关连的信息,<linux/kernel.h>定义了 600 - pr_debug()和pr_info()。 573 + <linux/device.h> 里有一些驱动模型诊断宏,你应该使用它们,以确保信息对应于正确的 574 + 设备和驱动,并且被标记了正确的消息级别。这些宏有:dev_err(),dev_warn(), 575 + dev_info() 等等。对于那些不和某个特定设备相关连的信息,<linux/printk.h> 定义了 576 + pr_notice(),pr_info(),pr_warn(),pr_err() 和其他。 601 577 602 - 写出好的调试信息可以是一个很大的挑战;当你写出来之后,这些信息在远程除错的时候 603 - 就会成为极大的帮助。当DEBUG符号没有被定义的时候,这些信息不应该被编译进内核里 604 - (也就是说,默认地,它们不应该被包含在内)。如果你使用dev_dbg()或者pr_debug(), 605 - 就能自动达到这个效果。很多子系统拥有Kconfig选项来启用-DDEBUG。还有一个相关的惯例 606 - 是使用VERBOSE_DEBUG来添加dev_vdbg()消息到那些已经由DEBUG启用的消息之上。 578 + 写出好的调试信息可以是一个很大的挑战;一旦你写出后,这些信息在远程除错时能提供极大 579 + 的帮助。然而打印调试信息的处理方式同打印非调试信息不同。其他 pr_XXX() 函数能无条件地 580 + 打印,pr_debug() 却不;默认情况下它不会被编译,除非定义了 DEBUG 或设定了 581 + CONFIG_DYNAMIC_DEBUG。实际这同样是为了 dev_dbg(),一个相关约定是在一个已经开启了 582 + DEBUG 时,使用 VERBOSE_DEBUG 来添加 dev_vdbg()。 583 + 584 + 许多子系统拥有 Kconfig 调试选项来开启 -DDEBUG 在对应的 Makefile 里面;在其他 585 + 情况下,特殊文件使用 #define DEBUG。当一条调试信息需要被无条件打印时,例如,如果 586 + 已经包含一个调试相关的 #ifdef 条件,printk(KERN_DEBUG ...) 就可被使用。 607 587 608 588 609 589 第十四章:分配内存 610 590 611 - 内核提供了下面的一般用途的内存分配函数:kmalloc(),kzalloc(),kcalloc()和 612 - vmalloc()。请参考API文档以获取有关它们的详细信息。 591 + 内核提供了下面的一般用途的内存分配函数: 592 + kmalloc(),kzalloc(),kmalloc_array(),kcalloc(),vmalloc() 和 vzalloc()。 593 + 请参考 API 文档以获取有关它们的详细信息。 613 594 614 595 传递结构体大小的首选形式是这样的: 615 596 616 597 p = kmalloc(sizeof(*p), ...); 617 598 618 - 另外一种传递方式中,sizeof的操作数是结构体的名字,这样会降低可读性,并且可能会引 619 - 入bug。有可能指针变量类型被改变时,而对应的传递给内存分配函数的sizeof的结果不变。 599 + 另外一种传递方式中,sizeof 的操作数是结构体的名字,这样会降低可读性,并且可能会引 600 + 入 bug。有可能指针变量类型被改变时,而对应的传递给内存分配函数的 sizeof 的结果不变。 620 601 621 - 强制转换一个void指针返回值是多余的。C语言本身保证了从void指针到其他任何指针类型 602 + 强制转换一个 void 指针返回值是多余的。C 语言本身保证了从 void 指针到其他任何指针类型 622 603 的转换是没有问题的。 604 + 605 + 分配一个数组的首选形式是这样的: 606 + 607 + p = kmalloc_array(n, sizeof(...), ...); 608 + 609 + 分配一个零长数组的首选形式是这样的: 610 + 611 + p = kcalloc(n, sizeof(...), ...); 612 + 613 + 两种形式检查分配大小 n * sizeof(...) 的溢出,如果溢出返回 NULL。 623 614 624 615 625 616 第十五章:内联弊病 626 617 627 - 有一个常见的误解是内联函数是gcc提供的可以让代码运行更快的一个选项。虽然使用内联 618 + 有一个常见的误解是内联函数是 gcc 提供的可以让代码运行更快的一个选项。虽然使用内联 628 619 函数有时候是恰当的(比如作为一种替代宏的方式,请看第十二章),不过很多情况下不是 629 - 这样。inline关键字的过度使用会使内核变大,从而使整个系统运行速度变慢。因为大内核 620 + 这样。inline 关键字的过度使用会使内核变大,从而使整个系统运行速度变慢。因为大内核 630 621 会占用更多的指令高速缓存(译注:一级缓存通常是指令缓存和数据缓存分开的)而且会导 631 - 致pagecache的可用内存减少。想象一下,一次pagecache未命中就会导致一次磁盘寻址,将 632 - 耗时5毫秒。5毫秒的时间内CPU能执行很多很多指令。 622 + 致 pagecache 的可用内存减少。想象一下,一次pagecache未命中就会导致一次磁盘寻址, 623 + 将耗时 5 毫秒。5 毫秒的时间内 CPU 能执行很多很多指令。 633 624 634 - 一个基本的原则是如果一个函数有3行以上,就不要把它变成内联函数。这个原则的一个例 625 + 一个基本的原则是如果一个函数有 3 行以上,就不要把它变成内联函数。这个原则的一个例 635 626 外是,如果你知道某个参数是一个编译时常量,而且因为这个常量你确定编译器在编译时能 636 - 优化掉你的函数的大部分代码,那仍然可以给它加上inline关键字。kmalloc()内联函数就 627 + 优化掉你的函数的大部分代码,那仍然可以给它加上 inline 关键字。kmalloc() 内联函数就 637 628 是一个很好的例子。 638 629 639 - 人们经常主张给static的而且只用了一次的函数加上inline,如此不会有任何损失,因为没 640 - 有什么好权衡的。虽然从技术上说这是正确的,但是实际上这种情况下即使不加inline gcc 641 - 也可以自动使其内联。而且其他用户可能会要求移除inline,由此而来的争论会抵消inline 630 + 人们经常主张给 static 的而且只用了一次的函数加上 inline,如此不会有任何损失,因为没 631 + 有什么好权衡的。虽然从技术上说这是正确的,但是实际上这种情况下即使不加 inline gcc 632 + 也可以自动使其内联。而且其他用户可能会要求移除 inline,由此而来的争论会抵消 inline 642 633 自身的潜在价值,得不偿失。 643 634 644 635 ··· 674 613 的一个值可以表示为一个错误代码整数(-Exxx=失败,0=成功)或者一个“成功”布尔值( 675 614 0=失败,非0=成功)。 676 615 677 - 混合使用这两种表达方式是难于发现的bug的来源。如果C语言本身严格区分整形和布尔型变 678 - 量,那么编译器就能够帮我们发现这些错误……不过C语言不区分。为了避免产生这种bug,请 616 + 混合使用这两种表达方式是难于发现的 bug 的来源。如果 C 语言本身严格区分整形和布尔型变 617 + 量,那么编译器就能够帮我们发现这些错误……不过 C 语言不区分。为了避免产生这种 bug,请 679 618 遵循下面的惯例: 680 619 681 620 如果函数的名字是一个动作或者强制性的命令,那么这个函数应该返回错误代码整 682 621 数。如果是一个判断,那么函数应该返回一个“成功”布尔值。 683 622 684 - 比如,“add work”是一个命令,所以add_work()函数在成功时返回0,在失败时返回-EBUSY。 685 - 类似的,因为“PCI device present”是一个判断,所以pci_dev_present()函数在成功找到 686 - 一个匹配的设备时应该返回1,如果找不到时应该返回0。 623 + 比如,“add work” 是一个命令,所以 add_work() 函数在成功时返回 0,在失败时返回 -EBUSY。 624 + 类似的,因为 “PCI device present” 是一个判断,所以 pci_dev_present() 函数在成功找到 625 + 一个匹配的设备时应该返回 1,如果找不到时应该返回 0。 687 626 688 627 所有导出(译注:EXPORT)的函数都必须遵守这个惯例,所有的公共函数也都应该如此。私 689 628 有(static)函数不需要如此,但是我们也推荐这样做。 690 629 691 630 返回值是实际计算结果而不是计算是否成功的标志的函数不受此惯例的限制。一般的,他们 692 631 通过返回一些正常值范围之外的结果来表示出错。典型的例子是返回指针的函数,他们使用 693 - NULL或者ERR_PTR机制来报告错误。 632 + NULL 或者 ERR_PTR 机制来报告错误。 694 633 695 634 696 635 第十七章:不要重新发明内核宏 697 636 698 - 头文件include/linux/kernel.h包含了一些宏,你应该使用它们,而不要自己写一些它们的 637 + 头文件 include/linux/kernel.h 包含了一些宏,你应该使用它们,而不要自己写一些它们的 699 638 变种。比如,如果你需要计算一个数组的长度,使用这个宏 700 639 701 - #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) 640 + #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) 702 641 703 642 类似的,如果你要计算某结构体成员的大小,使用 704 643 705 - #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f)) 644 + #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f)) 706 645 707 - 还有可以做严格的类型检查的min()和max()宏,如果你需要可以使用它们。你可以自己看看 646 + 还有可以做严格的类型检查的 min() 和 max() 宏,如果你需要可以使用它们。你可以自己看看 708 647 那个头文件里还定义了什么你可以拿来用的东西,如果有定义的话,你就不应在你的代码里 709 648 自己重新定义。 710 649 ··· 714 653 有一些编辑器可以解释嵌入在源文件里的由一些特殊标记标明的配置信息。比如,emacs 715 654 能够解释被标记成这样的行: 716 655 717 - -*- mode: c -*- 656 + -*- mode: c -*- 718 657 719 658 或者这样的: 720 659 721 - /* 722 - Local Variables: 723 - compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c" 724 - End: 725 - */ 660 + /* 661 + Local Variables: 662 + compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c" 663 + End: 664 + */ 726 665 727 - Vim能够解释这样的标记: 666 + Vim 能够解释这样的标记: 728 667 729 - /* vim:set sw=8 noet */ 668 + /* vim:set sw=8 noet */ 730 669 731 670 不要在源代码中包含任何这样的内容。每个人都有他自己的编辑器配置,你的源文件不应 732 671 该覆盖别人的配置。这包括有关缩进和模式配置的标记。人们可以使用他们自己定制的模 733 672 式,或者使用其他可以产生正确的缩进的巧妙方法。 734 673 735 674 675 + 第十九章:内联汇编 676 + 677 + 在特定架构的代码中,你也许需要内联汇编来使用 CPU 接口和平台相关功能。在需要 678 + 这么做时,不要犹豫。然而,当 C 可以完成工作时,不要无端地使用内联汇编。如果 679 + 可能,你可以并且应该用 C 和硬件交互。 680 + 681 + 考虑去写通用一点的内联汇编作为简明的辅助函数,而不是重复写下它们的细节。记住 682 + 内联汇编可以使用 C 参数。 683 + 684 + 大而特殊的汇编函数应该放在 .S 文件中,对应 C 的原型定义在 C 头文件中。汇编 685 + 函数的 C 原型应该使用 “asmlinkage”。 686 + 687 + 你可能需要将你的汇编语句标记为 volatile,来阻止 GCC 在没发现任何副作用后就 688 + 移除了它。你不必总是这样做,虽然,这样可以限制不必要的优化。 689 + 690 + 在写一个包含多条指令的单个内联汇编语句时,把每条指令用引号字符串分离,并写在 691 + 单独一行,在每个字符串结尾,除了 \n\t 结尾之外,在汇编输出中适当地缩进下 692 + 一条指令: 693 + 694 + asm ("magic %reg1, #42\n\t" 695 + "more_magic %reg2, %reg3" 696 + : /* outputs */ : /* inputs */ : /* clobbers */); 697 + 698 + 699 + 第二十章:条件编译 700 + 701 + 只要可能,就不要在 .c 文件里面使用预处理条件;这样做让代码更难阅读并且逻辑难以 702 + 跟踪。替代方案是,在头文件定义函数在这些 .c 文件中使用这类的条件表达式,提供空 703 + 操作的桩版本(译注:桩程序,是指用来替换一部分功能的程序段)在 #else 情况下, 704 + 再从 .c 文件中无条件地调用这些函数。编译器会避免生成任何桩调用的代码,产生一致 705 + 的结果,但逻辑将更加清晰。 706 + 707 + 宁可编译整个函数,而不是部分函数或部分表达式。而不是在一个表达式添加 ifdef, 708 + 解析部分或全部表达式到一个单独的辅助函数,并应用条件到该函数内。 709 + 710 + 如果你有一个在特定配置中可能是未使用的函数或变量,编译器将警告它定义了但未使用, 711 + 标记这个定义为 __maybe_unused 而不是将它包含在一个预处理条件中。(然而,如果 712 + 一个函数或变量总是未使用的,就直接删除它。) 713 + 714 + 在代码中,可能的情况下,使用 IS_ENABLED 宏来转化某个 Kconfig 标记为 C 的布尔 715 + 表达式,并在正常的 C 条件中使用它: 716 + 717 + if (IS_ENABLED(CONFIG_SOMETHING)) { 718 + ... 719 + } 720 + 721 + 编译器会无条件地做常数合并,就像使用 #ifdef 那样,包含或排除代码块,所以这不会 722 + 带来任何运行时开销。然而,这种方法依旧允许 C 编译器查看块内的代码,并检查它的正确 723 + 性(语法,类型,符号引用,等等)。因此,如果条件不满足,代码块内的引用符号将不存在, 724 + 你必须继续使用 #ifdef。 725 + 726 + 在任何有意义的 #if 或 #ifdef 块的末尾(超过几行),在 #endif 同一行的后面写下 727 + 注释,指出该条件表达式被使用。例如: 728 + 729 + #ifdef CONFIG_SOMETHING 730 + ... 731 + #endif /* CONFIG_SOMETHING */ 732 + 736 733 737 734 附录 I:参考 738 735 739 - The C Programming Language, 第二版, 作者Brian W. Kernighan和Denni 740 - M. Ritchie. Prentice Hall, Inc., 1988. ISBN 0-13-110362-8 (软皮), 741 - 0-13-110370-9 (硬皮). URL: http://cm.bell-labs.com/cm/cs/cbook/ 736 + The C Programming Language, 第二版 737 + 作者:Brian W. Kernighan 和 Denni M. Ritchie. 738 + Prentice Hall, Inc., 1988. 739 + ISBN 0-13-110362-8 (软皮), 0-13-110370-9 (硬皮). 742 740 743 - The Practice of Programming 作者Brian W. Kernighan和Rob Pike. Addison-Wesley, 744 - Inc., 1999. ISBN 0-201-61586-X. URL: http://cm.bell-labs.com/cm/cs/tpop/ 741 + The Practice of Programming 742 + 作者:Brian W. Kernighan 和 Rob Pike. 743 + Addison-Wesley, Inc., 1999. 744 + ISBN 0-201-61586-X. 745 745 746 - cpp,gcc,gcc internals和indent的GNU手册——和K&R及本文相符合的部分,全部可以在 747 - http://www.gnu.org/manual/找到 746 + GNU 手册 - 遵循 K&R 标准和此文本 - cpp, gcc, gcc internals and indent, 747 + 都可以从 http://www.gnu.org/manual/ 找到 748 748 749 749 WG14是C语言的国际标准化工作组,URL: http://www.open-std.org/JTC1/SC22/WG14/ 750 750 751 - Kernel CodingStyle,作者greg@kroah.com发表于OLS 2002: 751 + Kernel CodingStyle,作者 greg@kroah.com 发表于OLS 2002: 752 752 http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/ 753 - 754 - -- 755 - 最后更新于2007年7月13日。
+6 -1
Makefile
··· 1366 1366 @$(MAKE) $(build)=$(package-dir) help 1367 1367 @echo '' 1368 1368 @echo 'Documentation targets:' 1369 + @$(MAKE) -f $(srctree)/Documentation/Makefile.sphinx dochelp 1370 + @echo '' 1369 1371 @$(MAKE) -f $(srctree)/Documentation/DocBook/Makefile dochelp 1370 1372 @echo '' 1371 1373 @echo 'Architecture specific targets ($(SRCARCH)):' ··· 1416 1414 1417 1415 # Documentation targets 1418 1416 # --------------------------------------------------------------------------- 1419 - %docs: scripts_basic FORCE 1417 + DOC_TARGETS := xmldocs sgmldocs psdocs pdfdocs htmldocs mandocs installmandocs epubdocs cleandocs cleanmediadocs 1418 + PHONY += $(DOC_TARGETS) 1419 + $(DOC_TARGETS): scripts_basic FORCE 1420 1420 $(Q)$(MAKE) $(build)=scripts build_docproc build_check-lc_ctype 1421 + $(Q)$(MAKE) $(build)=Documentation -f $(srctree)/Documentation/Makefile.sphinx $@ 1421 1422 $(Q)$(MAKE) $(build)=Documentation/DocBook $@ 1422 1423 1423 1424 else # KBUILD_EXTMOD
+307 -152
scripts/kernel-doc
··· 59 59 -text Output plain text format. 60 60 61 61 Output selection (mutually exclusive): 62 + -export Only output documentation for symbols that have been 63 + exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL() 64 + in any input FILE or -export-file FILE. 65 + -internal Only output documentation for symbols that have NOT been 66 + exported using EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL() 67 + in any input FILE or -export-file FILE. 62 68 -function NAME Only output documentation for the given function(s) 63 69 or DOC: section title(s). All other functions and DOC: 64 70 sections are ignored. May be specified multiple times. ··· 74 68 75 69 Output selection modifiers: 76 70 -no-doc-sections Do not output DOC: sections. 71 + -enable-lineno Enable output of #define LINENO lines. Only works with 72 + reStructuredText format. 73 + -export-file FILE Specify an additional FILE in which to look for 74 + EXPORT_SYMBOL() and EXPORT_SYMBOL_GPL(). To be used with 75 + -export or -internal. May be specified multiple times. 77 76 78 77 Other parameters: 79 78 -v Verbose output, more warnings and other information. ··· 217 206 my $type_env = '(\$\w+)'; 218 207 my $type_enum_full = '\&(enum)\s*([_\w]+)'; 219 208 my $type_struct_full = '\&(struct)\s*([_\w]+)'; 209 + my $type_typedef_full = '\&(typedef)\s*([_\w]+)'; 210 + my $type_union_full = '\&(union)\s*([_\w]+)'; 211 + my $type_member = '\&([_\w]+)((\.|->)[_\w]+)'; 212 + my $type_member_func = $type_member . '\(\)'; 220 213 221 214 # Output conversion substitutions. 222 215 # One for each output format ··· 289 274 # rst-mode 290 275 my @highlights_rst = ( 291 276 [$type_constant, "``\$1``"], 292 - [$type_func, "\\:c\\:func\\:`\$1`"], 277 + # Note: need to escape () to avoid func matching later 278 + [$type_member_func, "\\:c\\:type\\:`\$1\$2\\\\(\\\\) <\$1>`"], 279 + [$type_member, "\\:c\\:type\\:`\$1\$2 <\$1>`"], 280 + [$type_func, "\\:c\\:func\\:`\$1()`"], 293 281 [$type_struct_full, "\\:c\\:type\\:`\$1 \$2 <\$2>`"], 294 282 [$type_enum_full, "\\:c\\:type\\:`\$1 \$2 <\$2>`"], 295 - [$type_struct, "\\:c\\:type\\:`struct \$1 <\$1>`"], 283 + [$type_typedef_full, "\\:c\\:type\\:`\$1 \$2 <\$2>`"], 284 + [$type_union_full, "\\:c\\:type\\:`\$1 \$2 <\$2>`"], 285 + # in rst this can refer to any type 286 + [$type_struct, "\\:c\\:type\\:`\$1`"], 296 287 [$type_param, "**\$1**"] 297 288 ); 298 289 my $blankline_rst = "\n"; ··· 324 303 my $output_mode = "man"; 325 304 my $output_preformatted = 0; 326 305 my $no_doc_sections = 0; 306 + my $enable_lineno = 0; 327 307 my @highlights = @highlights_man; 328 308 my $blankline = $blankline_man; 329 309 my $modulename = "Kernel API"; 330 - my $function_only = 0; 310 + 311 + use constant { 312 + OUTPUT_ALL => 0, # output all symbols and doc sections 313 + OUTPUT_INCLUDE => 1, # output only specified symbols 314 + OUTPUT_EXCLUDE => 2, # output everything except specified symbols 315 + OUTPUT_EXPORTED => 3, # output exported symbols 316 + OUTPUT_INTERNAL => 4, # output non-exported symbols 317 + }; 318 + my $output_selection = OUTPUT_ALL; 331 319 my $show_not_found = 0; 320 + 321 + my @export_file_list; 332 322 333 323 my @build_time; 334 324 if (defined($ENV{'KBUILD_BUILD_TIMESTAMP'}) && ··· 359 327 # CAVEAT EMPTOR! Some of the others I localised may not want to be, which 360 328 # could cause "use of undefined value" or other bugs. 361 329 my ($function, %function_table, %parametertypes, $declaration_purpose); 330 + my $declaration_start_line; 362 331 my ($type, $declaration_name, $return_type); 363 332 my ($newsection, $newcontents, $prototype, $brcount, %source_map); 364 333 ··· 377 344 378 345 my $lineprefix=""; 379 346 380 - # states 381 - # 0 - normal code 382 - # 1 - looking for function name 383 - # 2 - scanning field start. 384 - # 3 - scanning prototype. 385 - # 4 - documentation block 386 - # 5 - gathering documentation outside main block 347 + # Parser states 348 + use constant { 349 + STATE_NORMAL => 0, # normal code 350 + STATE_NAME => 1, # looking for function name 351 + STATE_FIELD => 2, # scanning field start 352 + STATE_PROTO => 3, # scanning prototype 353 + STATE_DOCBLOCK => 4, # documentation block 354 + STATE_INLINE => 5, # gathering documentation outside main block 355 + }; 387 356 my $state; 388 357 my $in_doc_sect; 389 358 390 - # Split Doc State 391 - # 0 - Invalid (Before start or after finish) 392 - # 1 - Is started (the /** was found inside a struct) 393 - # 2 - The @parameter header was found, start accepting multi paragraph text. 394 - # 3 - Finished (the */ was found) 395 - # 4 - Error - Comment without header was found. Spit a warning as it's not 396 - # proper kernel-doc and ignore the rest. 397 - my $split_doc_state; 359 + # Inline documentation state 360 + use constant { 361 + STATE_INLINE_NA => 0, # not applicable ($state != STATE_INLINE) 362 + STATE_INLINE_NAME => 1, # looking for member name (@foo:) 363 + STATE_INLINE_TEXT => 2, # looking for member documentation 364 + STATE_INLINE_END => 3, # done 365 + STATE_INLINE_ERROR => 4, # error - Comment without header was found. 366 + # Spit a warning as it's not 367 + # proper kernel-doc and ignore the rest. 368 + }; 369 + my $inline_doc_state; 398 370 399 371 #declaration types: can be 400 372 # 'function', 'struct', 'union', 'enum', 'typedef' 401 373 my $decl_type; 402 - 403 - my $doc_special = "\@\%\$\&"; 404 374 405 375 my $doc_start = '^/\*\*\s*$'; # Allow whitespace at end of comment start. 406 376 my $doc_end = '\*/'; 407 377 my $doc_com = '\s*\*\s*'; 408 378 my $doc_com_body = '\s*\* ?'; 409 379 my $doc_decl = $doc_com . '(\w+)'; 410 - my $doc_sect = $doc_com . '([' . $doc_special . ']?[\w\s]+):(.*)'; 380 + # @params and a strictly limited set of supported section names 381 + my $doc_sect = $doc_com . 382 + '\s*(\@\w+|description|context|returns?|notes?|examples?)\s*:(.*)'; 411 383 my $doc_content = $doc_com_body . '(.*)'; 412 384 my $doc_block = $doc_com . 'DOC:\s*(.*)?'; 413 - my $doc_split_start = '^\s*/\*\*\s*$'; 414 - my $doc_split_sect = '\s*\*\s*(@[\w\s]+):(.*)'; 415 - my $doc_split_end = '^\s*\*/\s*$'; 385 + my $doc_inline_start = '^\s*/\*\*\s*$'; 386 + my $doc_inline_sect = '\s*\*\s*(@[\w\s]+):(.*)'; 387 + my $doc_inline_end = '^\s*\*/\s*$'; 388 + my $export_symbol = '^\s*EXPORT_SYMBOL(_GPL)?\s*\(\s*(\w+)\s*\)\s*;'; 416 389 417 - my %constants; 418 390 my %parameterdescs; 391 + my %parameterdesc_start_lines; 419 392 my @parameterlist; 420 393 my %sections; 421 394 my @sectionlist; 395 + my %section_start_lines; 422 396 my $sectcheck; 423 397 my $struct_actual; 424 398 425 399 my $contents = ""; 400 + my $new_start_line = 0; 401 + 402 + # the canonical section names. see also $doc_sect above. 426 403 my $section_default = "Description"; # default section 427 404 my $section_intro = "Introduction"; 428 405 my $section = $section_default; ··· 480 437 } elsif ($cmd eq "-module") { # not needed for XML, inherits from calling document 481 438 $modulename = shift @ARGV; 482 439 } elsif ($cmd eq "-function") { # to only output specific functions 483 - $function_only = 1; 440 + $output_selection = OUTPUT_INCLUDE; 484 441 $function = shift @ARGV; 485 442 $function_table{$function} = 1; 486 - } elsif ($cmd eq "-nofunction") { # to only output specific functions 487 - $function_only = 2; 443 + } elsif ($cmd eq "-nofunction") { # output all except specific functions 444 + $output_selection = OUTPUT_EXCLUDE; 488 445 $function = shift @ARGV; 489 446 $function_table{$function} = 1; 447 + } elsif ($cmd eq "-export") { # only exported symbols 448 + $output_selection = OUTPUT_EXPORTED; 449 + %function_table = (); 450 + } elsif ($cmd eq "-internal") { # only non-exported symbols 451 + $output_selection = OUTPUT_INTERNAL; 452 + %function_table = (); 453 + } elsif ($cmd eq "-export-file") { 454 + my $file = shift @ARGV; 455 + push(@export_file_list, $file); 490 456 } elsif ($cmd eq "-v") { 491 457 $verbose = 1; 492 458 } elsif (($cmd eq "-h") || ($cmd eq "--help")) { 493 459 usage(); 494 460 } elsif ($cmd eq '-no-doc-sections') { 495 461 $no_doc_sections = 1; 462 + } elsif ($cmd eq '-enable-lineno') { 463 + $enable_lineno = 1; 496 464 } elsif ($cmd eq '-show-not-found') { 497 465 $show_not_found = 1; 498 466 } ··· 521 467 return $version; 522 468 } 523 469 470 + # 471 + sub print_lineno { 472 + my $lineno = shift; 473 + if ($enable_lineno && defined($lineno)) { 474 + print "#define LINENO " . $lineno . "\n"; 475 + } 476 + } 524 477 ## 525 478 # dumps section contents to arrays/hashes intended for that purpose. 526 479 # ··· 536 475 my $name = shift; 537 476 my $contents = join "\n", @_; 538 477 539 - if ($name =~ m/$type_constant/) { 540 - $name = $1; 541 - # print STDERR "constant section '$1' = '$contents'\n"; 542 - $constants{$name} = $contents; 543 - } elsif ($name =~ m/$type_param/) { 544 - # print STDERR "parameter def '$1' = '$contents'\n"; 478 + if ($name =~ m/$type_param/) { 545 479 $name = $1; 546 480 $parameterdescs{$name} = $contents; 547 481 $sectcheck = $sectcheck . $name . " "; 482 + $parameterdesc_start_lines{$name} = $new_start_line; 483 + $new_start_line = 0; 548 484 } elsif ($name eq "@\.\.\.") { 549 - # print STDERR "parameter def '...' = '$contents'\n"; 550 485 $name = "..."; 551 486 $parameterdescs{$name} = $contents; 552 487 $sectcheck = $sectcheck . $name . " "; 488 + $parameterdesc_start_lines{$name} = $new_start_line; 489 + $new_start_line = 0; 553 490 } else { 554 - # print STDERR "other section '$name' = '$contents'\n"; 555 491 if (defined($sections{$name}) && ($sections{$name} ne "")) { 556 - print STDERR "${file}:$.: error: duplicate section name '$name'\n"; 557 - ++$errors; 492 + # Only warn on user specified duplicate section names. 493 + if ($name ne $section_default) { 494 + print STDERR "${file}:$.: warning: duplicate section name '$name'\n"; 495 + ++$warnings; 496 + } 497 + $sections{$name} .= $contents; 498 + } else { 499 + $sections{$name} = $contents; 500 + push @sectionlist, $name; 501 + $section_start_lines{$name} = $new_start_line; 502 + $new_start_line = 0; 558 503 } 559 - $sections{$name} = $contents; 560 - push @sectionlist, $name; 561 504 } 562 505 } 563 506 ··· 577 512 return; 578 513 } 579 514 580 - if (($function_only == 0) || 581 - ( $function_only == 1 && defined($function_table{$name})) || 582 - ( $function_only == 2 && !defined($function_table{$name}))) 515 + if (($output_selection == OUTPUT_ALL) || 516 + ($output_selection == OUTPUT_INCLUDE && 517 + defined($function_table{$name})) || 518 + ($output_selection == OUTPUT_EXCLUDE && 519 + !defined($function_table{$name}))) 583 520 { 584 521 dump_section($file, $name, $contents); 585 522 output_blockhead({'sectionlist' => \@sectionlist, 586 523 'sections' => \%sections, 587 524 'module' => $modulename, 588 - 'content-only' => ($function_only != 0), }); 525 + 'content-only' => ($output_selection != OUTPUT_ALL), }); 589 526 } 590 527 } 591 528 ··· 1803 1736 my ($parameter, $section); 1804 1737 1805 1738 foreach $section (@{$args{'sectionlist'}}) { 1806 - print "**$section**\n\n"; 1739 + if ($output_selection != OUTPUT_INCLUDE) { 1740 + print "**$section**\n\n"; 1741 + } 1742 + print_lineno($section_start_lines{$section}); 1807 1743 output_highlight_rst($args{'sections'}{$section}); 1808 1744 print "\n"; 1809 1745 } ··· 1823 1753 die $@ if $@; 1824 1754 1825 1755 foreach $line (split "\n", $contents) { 1826 - if ($line eq "") { 1827 - print $lineprefix, $blankline; 1828 - } else { 1829 - $line =~ s/\\\\\\/\&/g; 1830 - print $lineprefix, $line; 1831 - } 1832 - print "\n"; 1756 + print $lineprefix . $line . "\n"; 1833 1757 } 1834 1758 } 1835 1759 1836 1760 sub output_function_rst(%) { 1837 1761 my %args = %{$_[0]}; 1838 1762 my ($parameter, $section); 1763 + my $oldprefix = $lineprefix; 1839 1764 my $start; 1840 1765 1841 1766 print ".. c:function:: "; ··· 1848 1783 } 1849 1784 $count++; 1850 1785 $type = $args{'parametertypes'}{$parameter}; 1786 + 1787 + # RST doesn't like address_space tags at function prototypes 1788 + $type =~ s/__(user|kernel|iomem|percpu|pmem|rcu)\s*//; 1789 + 1851 1790 if ($type =~ m/([^\(]*\(\*)\s*\)\s*\(([^\)]*)\)/) { 1852 1791 # pointer-to-function 1853 1792 print $1 . $parameter . ") (" . $2; ··· 1859 1790 print $type . " " . $parameter; 1860 1791 } 1861 1792 } 1862 - print ")\n\n " . $args{'purpose'} . "\n\n"; 1793 + print ")\n\n"; 1794 + print_lineno($declaration_start_line); 1795 + $lineprefix = " "; 1796 + output_highlight_rst($args{'purpose'}); 1797 + print "\n"; 1863 1798 1864 - print ":Parameters:\n\n"; 1799 + print "**Parameters**\n\n"; 1800 + $lineprefix = " "; 1865 1801 foreach $parameter (@{$args{'parameterlist'}}) { 1866 1802 my $parameter_name = $parameter; 1867 1803 #$parameter_name =~ s/\[.*//; 1868 1804 $type = $args{'parametertypes'}{$parameter}; 1869 1805 1870 1806 if ($type ne "") { 1871 - print " ``$type $parameter``\n"; 1807 + print "``$type $parameter``\n"; 1872 1808 } else { 1873 - print " ``$parameter``\n"; 1809 + print "``$parameter``\n"; 1874 1810 } 1875 - if ($args{'parameterdescs'}{$parameter_name} ne $undescribed) { 1876 - my $oldprefix = $lineprefix; 1877 - $lineprefix = " "; 1811 + 1812 + print_lineno($parameterdesc_start_lines{$parameter_name}); 1813 + 1814 + if (defined($args{'parameterdescs'}{$parameter_name}) && 1815 + $args{'parameterdescs'}{$parameter_name} ne $undescribed) { 1878 1816 output_highlight_rst($args{'parameterdescs'}{$parameter_name}); 1879 - $lineprefix = $oldprefix; 1880 1817 } else { 1881 - print "\n _undescribed_\n"; 1818 + print " *undescribed*\n"; 1882 1819 } 1883 1820 print "\n"; 1884 1821 } 1822 + 1823 + $lineprefix = $oldprefix; 1885 1824 output_section_rst(@_); 1886 1825 } 1887 1826 ··· 1897 1820 my %args = %{$_[0]}; 1898 1821 my $section; 1899 1822 my $oldprefix = $lineprefix; 1900 - $lineprefix = " "; 1823 + $lineprefix = ""; 1901 1824 1902 1825 foreach $section (@{$args{'sectionlist'}}) { 1903 - print ":$section:\n\n"; 1826 + print "**$section**\n\n"; 1827 + print_lineno($section_start_lines{$section}); 1904 1828 output_highlight_rst($args{'sections'}{$section}); 1905 1829 print "\n"; 1906 1830 } ··· 1912 1834 sub output_enum_rst(%) { 1913 1835 my %args = %{$_[0]}; 1914 1836 my ($parameter); 1837 + my $oldprefix = $lineprefix; 1915 1838 my $count; 1916 1839 my $name = "enum " . $args{'enum'}; 1917 1840 1918 1841 print "\n\n.. c:type:: " . $name . "\n\n"; 1919 - print " " . $args{'purpose'} . "\n\n"; 1842 + print_lineno($declaration_start_line); 1843 + $lineprefix = " "; 1844 + output_highlight_rst($args{'purpose'}); 1845 + print "\n"; 1920 1846 1921 - print "..\n\n:Constants:\n\n"; 1922 - my $oldprefix = $lineprefix; 1923 - $lineprefix = " "; 1847 + print "**Constants**\n\n"; 1848 + $lineprefix = " "; 1924 1849 foreach $parameter (@{$args{'parameterlist'}}) { 1925 - print " `$parameter`\n"; 1850 + print "``$parameter``\n"; 1926 1851 if ($args{'parameterdescs'}{$parameter} ne $undescribed) { 1927 1852 output_highlight_rst($args{'parameterdescs'}{$parameter}); 1928 1853 } else { 1929 - print " undescribed\n"; 1854 + print " *undescribed*\n"; 1930 1855 } 1931 1856 print "\n"; 1932 1857 } 1858 + 1933 1859 $lineprefix = $oldprefix; 1934 1860 output_section_rst(@_); 1935 1861 } ··· 1941 1859 sub output_typedef_rst(%) { 1942 1860 my %args = %{$_[0]}; 1943 1861 my ($parameter); 1944 - my $count; 1862 + my $oldprefix = $lineprefix; 1945 1863 my $name = "typedef " . $args{'typedef'}; 1946 1864 1947 - ### FIXME: should the name below contain "typedef" or not? 1948 1865 print "\n\n.. c:type:: " . $name . "\n\n"; 1949 - print " " . $args{'purpose'} . "\n\n"; 1866 + print_lineno($declaration_start_line); 1867 + $lineprefix = " "; 1868 + output_highlight_rst($args{'purpose'}); 1869 + print "\n"; 1950 1870 1871 + $lineprefix = $oldprefix; 1951 1872 output_section_rst(@_); 1952 1873 } 1953 1874 1954 1875 sub output_struct_rst(%) { 1955 1876 my %args = %{$_[0]}; 1956 1877 my ($parameter); 1878 + my $oldprefix = $lineprefix; 1957 1879 my $name = $args{'type'} . " " . $args{'struct'}; 1958 1880 1959 1881 print "\n\n.. c:type:: " . $name . "\n\n"; 1960 - print " " . $args{'purpose'} . "\n\n"; 1882 + print_lineno($declaration_start_line); 1883 + $lineprefix = " "; 1884 + output_highlight_rst($args{'purpose'}); 1885 + print "\n"; 1961 1886 1962 - print ":Definition:\n\n"; 1963 - print " ::\n\n"; 1887 + print "**Definition**\n\n"; 1888 + print "::\n\n"; 1964 1889 print " " . $args{'type'} . " " . $args{'struct'} . " {\n"; 1965 1890 foreach $parameter (@{$args{'parameterlist'}}) { 1966 1891 if ($parameter =~ /^#/) { 1967 - print " " . "$parameter\n"; 1892 + print " " . "$parameter\n"; 1968 1893 next; 1969 1894 } 1970 1895 ··· 1992 1903 } 1993 1904 print " };\n\n"; 1994 1905 1995 - print ":Members:\n\n"; 1906 + print "**Members**\n\n"; 1907 + $lineprefix = " "; 1996 1908 foreach $parameter (@{$args{'parameterlist'}}) { 1997 1909 ($parameter =~ /^#/) && next; 1998 1910 ··· 2002 1912 2003 1913 ($args{'parameterdescs'}{$parameter_name} ne $undescribed) || next; 2004 1914 $type = $args{'parametertypes'}{$parameter}; 2005 - print " `$type $parameter`" . "\n"; 2006 - my $oldprefix = $lineprefix; 2007 - $lineprefix = " "; 1915 + print_lineno($parameterdesc_start_lines{$parameter_name}); 1916 + print "``$type $parameter``\n"; 2008 1917 output_highlight_rst($args{'parameterdescs'}{$parameter_name}); 2009 - $lineprefix = $oldprefix; 2010 1918 print "\n"; 2011 1919 } 2012 1920 print "\n"; 1921 + 1922 + $lineprefix = $oldprefix; 2013 1923 output_section_rst(@_); 2014 1924 } 2015 1925 ··· 2059 1969 my $name = shift; 2060 1970 my $functype = shift; 2061 1971 my $func = "output_${functype}_$output_mode"; 2062 - if (($function_only==0) || 2063 - ( $function_only == 1 && defined($function_table{$name})) || 2064 - ( $function_only == 2 && !($functype eq "function" && defined($function_table{$name})))) 1972 + if (($output_selection == OUTPUT_ALL) || 1973 + (($output_selection == OUTPUT_INCLUDE || 1974 + $output_selection == OUTPUT_EXPORTED) && 1975 + defined($function_table{$name})) || 1976 + (($output_selection == OUTPUT_EXCLUDE || 1977 + $output_selection == OUTPUT_INTERNAL) && 1978 + !($functype eq "function" && defined($function_table{$name})))) 2065 1979 { 2066 1980 &$func(@_); 2067 1981 $section_counter++; ··· 2565 2471 2566 2472 sub reset_state { 2567 2473 $function = ""; 2568 - %constants = (); 2569 2474 %parameterdescs = (); 2570 2475 %parametertypes = (); 2571 2476 @parameterlist = (); ··· 2574 2481 $struct_actual = ""; 2575 2482 $prototype = ""; 2576 2483 2577 - $state = 0; 2578 - $split_doc_state = 0; 2484 + $state = STATE_NORMAL; 2485 + $inline_doc_state = STATE_INLINE_NA; 2579 2486 } 2580 2487 2581 2488 sub tracepoint_munge($) { ··· 2638 2545 } 2639 2546 } 2640 2547 2641 - sub process_state3_function($$) { 2548 + sub process_proto_function($$) { 2642 2549 my $x = shift; 2643 2550 my $file = shift; 2644 2551 ··· 2668 2575 } 2669 2576 } 2670 2577 2671 - sub process_state3_type($$) { 2578 + sub process_proto_type($$) { 2672 2579 my $x = shift; 2673 2580 my $file = shift; 2674 2581 ··· 2742 2649 return $text; 2743 2650 } 2744 2651 2652 + sub map_filename($) { 2653 + my $file; 2654 + my ($orig_file) = @_; 2655 + 2656 + if (defined($ENV{'SRCTREE'})) { 2657 + $file = "$ENV{'SRCTREE'}" . "/" . $orig_file; 2658 + } else { 2659 + $file = $orig_file; 2660 + } 2661 + 2662 + if (defined($source_map{$file})) { 2663 + $file = $source_map{$file}; 2664 + } 2665 + 2666 + return $file; 2667 + } 2668 + 2669 + sub process_export_file($) { 2670 + my ($orig_file) = @_; 2671 + my $file = map_filename($orig_file); 2672 + 2673 + if (!open(IN,"<$file")) { 2674 + print STDERR "Error: Cannot open file $file\n"; 2675 + ++$errors; 2676 + return; 2677 + } 2678 + 2679 + while (<IN>) { 2680 + if (/$export_symbol/) { 2681 + $function_table{$2} = 1; 2682 + } 2683 + } 2684 + 2685 + close(IN); 2686 + } 2687 + 2745 2688 sub process_file($) { 2746 2689 my $file; 2747 2690 my $identifier; ··· 2786 2657 my $in_purpose = 0; 2787 2658 my $initial_section_counter = $section_counter; 2788 2659 my ($orig_file) = @_; 2660 + my $leading_space; 2789 2661 2790 - if (defined($ENV{'SRCTREE'})) { 2791 - $file = "$ENV{'SRCTREE'}" . "/" . $orig_file; 2792 - } 2793 - else { 2794 - $file = $orig_file; 2795 - } 2796 - if (defined($source_map{$file})) { 2797 - $file = $source_map{$file}; 2798 - } 2662 + $file = map_filename($orig_file); 2799 2663 2800 2664 if (!open(IN,"<$file")) { 2801 2665 print STDERR "Error: Cannot open file $file\n"; ··· 2803 2681 while (s/\\\s*$//) { 2804 2682 $_ .= <IN>; 2805 2683 } 2806 - if ($state == 0) { 2684 + if ($state == STATE_NORMAL) { 2807 2685 if (/$doc_start/o) { 2808 - $state = 1; # next line is always the function name 2686 + $state = STATE_NAME; # next line is always the function name 2809 2687 $in_doc_sect = 0; 2688 + $declaration_start_line = $. + 1; 2810 2689 } 2811 - } elsif ($state == 1) { # this line is the function name (always) 2690 + } elsif ($state == STATE_NAME) {# this line is the function name (always) 2812 2691 if (/$doc_block/o) { 2813 - $state = 4; 2692 + $state = STATE_DOCBLOCK; 2814 2693 $contents = ""; 2694 + $new_start_line = $. + 1; 2695 + 2815 2696 if ( $1 eq "" ) { 2816 2697 $section = $section_intro; 2817 2698 } else { ··· 2827 2702 $identifier = $1; 2828 2703 } 2829 2704 2830 - $state = 2; 2705 + $state = STATE_FIELD; 2706 + # if there's no @param blocks need to set up default section 2707 + # here 2708 + $contents = ""; 2709 + $section = $section_default; 2710 + $new_start_line = $. + 1; 2831 2711 if (/-(.*)/) { 2832 2712 # strip leading/trailing/multiple spaces 2833 2713 $descr= $1; ··· 2870 2740 print STDERR "${file}:$.: warning: Cannot understand $_ on line $.", 2871 2741 " - I thought it was a doc line\n"; 2872 2742 ++$warnings; 2873 - $state = 0; 2743 + $state = STATE_NORMAL; 2874 2744 } 2875 - } elsif ($state == 2) { # look for head: lines, and include content 2876 - if (/$doc_sect/o) { 2745 + } elsif ($state == STATE_FIELD) { # look for head: lines, and include content 2746 + if (/$doc_sect/i) { # case insensitive for supported section names 2877 2747 $newsection = $1; 2878 2748 $newcontents = $2; 2749 + 2750 + # map the supported section names to the canonical names 2751 + if ($newsection =~ m/^description$/i) { 2752 + $newsection = $section_default; 2753 + } elsif ($newsection =~ m/^context$/i) { 2754 + $newsection = $section_context; 2755 + } elsif ($newsection =~ m/^returns?$/i) { 2756 + $newsection = $section_return; 2757 + } elsif ($newsection =~ m/^\@return$/) { 2758 + # special: @return is a section, not a param description 2759 + $newsection = $section_return; 2760 + } 2879 2761 2880 2762 if (($contents ne "") && ($contents ne "\n")) { 2881 2763 if (!$in_doc_sect && $verbose) { ··· 2901 2759 $in_doc_sect = 1; 2902 2760 $in_purpose = 0; 2903 2761 $contents = $newcontents; 2762 + $new_start_line = $.; 2763 + while ((substr($contents, 0, 1) eq " ") || 2764 + substr($contents, 0, 1) eq "\t") { 2765 + $contents = substr($contents, 1); 2766 + } 2904 2767 if ($contents ne "") { 2905 - while ((substr($contents, 0, 1) eq " ") || 2906 - substr($contents, 0, 1) eq "\t") { 2907 - $contents = substr($contents, 1); 2908 - } 2909 2768 $contents .= "\n"; 2910 2769 } 2911 2770 $section = $newsection; 2771 + $leading_space = undef; 2912 2772 } elsif (/$doc_end/) { 2913 2773 if (($contents ne "") && ($contents ne "\n")) { 2914 2774 dump_section($file, $section, xml_escape($contents)); ··· 2924 2780 } 2925 2781 2926 2782 $prototype = ""; 2927 - $state = 3; 2783 + $state = STATE_PROTO; 2928 2784 $brcount = 0; 2929 2785 # print STDERR "end of doc comment, looking for prototype\n"; 2930 2786 } elsif (/$doc_content/) { ··· 2935 2791 dump_section($file, $section, xml_escape($contents)); 2936 2792 $section = $section_default; 2937 2793 $contents = ""; 2794 + $new_start_line = $.; 2938 2795 } else { 2939 2796 $contents .= "\n"; 2940 2797 } ··· 2946 2801 $declaration_purpose .= " " . xml_escape($1); 2947 2802 $declaration_purpose =~ s/\s+/ /g; 2948 2803 } else { 2949 - $contents .= $1 . "\n"; 2804 + my $cont = $1; 2805 + if ($section =~ m/^@/ || $section eq $section_context) { 2806 + if (!defined $leading_space) { 2807 + if ($cont =~ m/^(\s+)/) { 2808 + $leading_space = $1; 2809 + } else { 2810 + $leading_space = ""; 2811 + } 2812 + } 2813 + 2814 + $cont =~ s/^$leading_space//; 2815 + } 2816 + $contents .= $cont . "\n"; 2950 2817 } 2951 2818 } else { 2952 2819 # i dont know - bad line? ignore. 2953 2820 print STDERR "${file}:$.: warning: bad line: $_"; 2954 2821 ++$warnings; 2955 2822 } 2956 - } elsif ($state == 5) { # scanning for split parameters 2823 + } elsif ($state == STATE_INLINE) { # scanning for inline parameters 2957 2824 # First line (state 1) needs to be a @parameter 2958 - if ($split_doc_state == 1 && /$doc_split_sect/o) { 2825 + if ($inline_doc_state == STATE_INLINE_NAME && /$doc_inline_sect/o) { 2959 2826 $section = $1; 2960 2827 $contents = $2; 2828 + $new_start_line = $.; 2961 2829 if ($contents ne "") { 2962 2830 while ((substr($contents, 0, 1) eq " ") || 2963 2831 substr($contents, 0, 1) eq "\t") { 2964 2832 $contents = substr($contents, 1); 2965 2833 } 2966 - $contents .= "\n"; 2834 + $contents .= "\n"; 2967 2835 } 2968 - $split_doc_state = 2; 2836 + $inline_doc_state = STATE_INLINE_TEXT; 2969 2837 # Documentation block end */ 2970 - } elsif (/$doc_split_end/) { 2838 + } elsif (/$doc_inline_end/) { 2971 2839 if (($contents ne "") && ($contents ne "\n")) { 2972 2840 dump_section($file, $section, xml_escape($contents)); 2973 2841 $section = $section_default; 2974 2842 $contents = ""; 2975 2843 } 2976 - $state = 3; 2977 - $split_doc_state = 0; 2844 + $state = STATE_PROTO; 2845 + $inline_doc_state = STATE_INLINE_NA; 2978 2846 # Regular text 2979 2847 } elsif (/$doc_content/) { 2980 - if ($split_doc_state == 2) { 2848 + if ($inline_doc_state == STATE_INLINE_TEXT) { 2981 2849 $contents .= $1 . "\n"; 2982 - } elsif ($split_doc_state == 1) { 2983 - $split_doc_state = 4; 2984 - print STDERR "Warning(${file}:$.): "; 2850 + # nuke leading blank lines 2851 + if ($contents =~ /^\s*$/) { 2852 + $contents = ""; 2853 + } 2854 + } elsif ($inline_doc_state == STATE_INLINE_NAME) { 2855 + $inline_doc_state = STATE_INLINE_ERROR; 2856 + print STDERR "${file}:$.: warning: "; 2985 2857 print STDERR "Incorrect use of kernel-doc format: $_"; 2986 2858 ++$warnings; 2987 2859 } 2988 2860 } 2989 - } elsif ($state == 3) { # scanning for function '{' (end of prototype) 2990 - if (/$doc_split_start/) { 2991 - $state = 5; 2992 - $split_doc_state = 1; 2861 + } elsif ($state == STATE_PROTO) { # scanning for function '{' (end of prototype) 2862 + if (/$doc_inline_start/) { 2863 + $state = STATE_INLINE; 2864 + $inline_doc_state = STATE_INLINE_NAME; 2993 2865 } elsif ($decl_type eq 'function') { 2994 - process_state3_function($_, $file); 2866 + process_proto_function($_, $file); 2995 2867 } else { 2996 - process_state3_type($_, $file); 2868 + process_proto_type($_, $file); 2997 2869 } 2998 - } elsif ($state == 4) { 2999 - # Documentation block 3000 - if (/$doc_block/) { 3001 - dump_doc_section($file, $section, xml_escape($contents)); 3002 - $contents = ""; 3003 - $function = ""; 3004 - %constants = (); 3005 - %parameterdescs = (); 3006 - %parametertypes = (); 3007 - @parameterlist = (); 3008 - %sections = (); 3009 - @sectionlist = (); 3010 - $prototype = ""; 3011 - if ( $1 eq "" ) { 3012 - $section = $section_intro; 3013 - } else { 3014 - $section = $1; 3015 - } 3016 - } 3017 - elsif (/$doc_end/) 2870 + } elsif ($state == STATE_DOCBLOCK) { 2871 + if (/$doc_end/) 3018 2872 { 3019 2873 dump_doc_section($file, $section, xml_escape($contents)); 2874 + $section = $section_default; 3020 2875 $contents = ""; 3021 2876 $function = ""; 3022 - %constants = (); 3023 2877 %parameterdescs = (); 3024 2878 %parametertypes = (); 3025 2879 @parameterlist = (); 3026 2880 %sections = (); 3027 2881 @sectionlist = (); 3028 2882 $prototype = ""; 3029 - $state = 0; 2883 + $state = STATE_NORMAL; 3030 2884 } 3031 2885 elsif (/$doc_content/) 3032 2886 { ··· 3042 2898 } 3043 2899 if ($initial_section_counter == $section_counter) { 3044 2900 print STDERR "${file}:1: warning: no structured comments found\n"; 3045 - if (($function_only == 1) && ($show_not_found == 1)) { 2901 + if (($output_selection == OUTPUT_INCLUDE) && ($show_not_found == 1)) { 3046 2902 print STDERR " Was looking for '$_'.\n" for keys %function_table; 3047 2903 } 3048 2904 if ($output_mode eq "xml") { ··· 3099 2955 $source_map{$relname} = $absname; 3100 2956 } 3101 2957 close(SOURCE_MAP); 2958 + } 2959 + 2960 + if ($output_selection == OUTPUT_EXPORTED || 2961 + $output_selection == OUTPUT_INTERNAL) { 2962 + 2963 + push(@export_file_list, @ARGV); 2964 + 2965 + foreach (@export_file_list) { 2966 + chomp; 2967 + process_export_file($_); 2968 + } 3102 2969 } 3103 2970 3104 2971 foreach (@ARGV) {