Merged revisions 140169 via svnmerge from
[asterisk-bristuff.git] / doc / CODING-GUIDELINES
blob985df6846d9a275e6d4817f78ef7e502ac1588bb
1             --------------------------------------
2             == Asterisk Coding Guidelines ==
3             --------------------------------------
5 This document gives some basic indication on how the asterisk code
6 is structured. The first part covers the structure and style of
7 individual files. The second part (TO BE COMPLETED) covers the
8 overall code structure and the build architecture.
10 Please read it to the end to understand in detail how the asterisk
11 code is organized, and to know how to extend asterisk or contribute
12 new code.
14 We are looking forward to your contributions to Asterisk - the 
15 Open Source PBX! As Asterisk is a large and in some parts very
16 time-sensitive application, the code base needs to conform to
17 a common set of coding rules so that many developers can enhance
18 and maintain the code. Code also needs to be reviewed and tested
19 so that it works and follows the general architecture and guide-
20 lines, and is well documented.
22 Asterisk is published under a dual-licensing scheme by Digium.
23 To be accepted into the codebase, all non-trivial changes must be
24 licensed to Digium. For more information, see the electronic license
25 agreement on http://bugs.digium.com/.
27 Patches should be in the form of a unified (-u) diff, made from a checkout
28 from subversion.
30 /usr/src/asterisk$ svn diff > mypatch
32 If you would like to only include changes to certain files in the patch, you
33 can list them in the "svn diff" command:
35 /usr/src/asterisk$ svn diff somefile.c someotherfile.c > mypatch
37                 -----------------------------------
38                 ==  PART ONE: CODING GUIDELINES  ==
39                 -----------------------------------
41 * General rules
42 ---------------
44 - All code, filenames, function names and comments must be in ENGLISH.
46 - Don't annotate your changes with comments like "/* JMG 4/20/04 */";
47   Comments should explain what the code does, not when something was changed
48   or who changed it. If you have done a larger contribution, make sure
49   that you are added to the CREDITS file.
51 - Don't make unnecessary whitespace changes throughout the code.
52   If you make changes, submit them to the tracker as separate patches
53   that only include whitespace and formatting changes.
55 - Don't use C++ type (//) comments.
57 - Try to match the existing formatting of the file you are working on.
59 - Use spaces instead of tabs when aligning in-line comments or #defines (this makes 
60   your comments aligned even if the code is viewed with another tabsize)
62 * File structure and header inclusion
63 -------------------------------------
65 Every C source file should start with a proper copyright
66 and a brief description of the content of the file.
67 Following that, you should immediately put the following lines:
69 #include "asterisk.h"
70 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
72 "asterisk.h" resolves OS and compiler dependencies for the basic
73 set of unix functions (data types, system calls, basic I/O
74 libraries) and the basic Asterisk APIs.
75 ASTERISK_FILE_VERSION() stores in the executable information
76 about the file.   
78 Next, you should #include extra headers according to the functionality
79 that your file uses or implements. For each group of functions that
80 you use there is a common header, which covers OS header dependencies
81 and defines the 'external' API of those functions (the equivalent
82 of 'public' members of a class).  As an example:
84     asterisk/module.h
85         if you are implementing a module, this should be included in one
86         of the files that are linked with the module.
88     asterisk/io.h
89         access to extra file I/O functions (stat, fstat, playing with
90         directories etc)
92     asterisk/network.h
93         basic network I/O - all of the socket library, select/poll,
94         and asterisk-specific (usually either thread-safe or reentrant
95         or both) functions to play with socket addresses.
97     asterisk/app.h
98         parsing of application arguments
100     asterisk/channel.h
101         struct ast_channel and functions to manipulate it
103 For more information look at the headers in include/asterisk/ .
104 These files are usually self-sufficient, i.e. they recursively #include
105 all the extra headers they need.
107 The equivalent of 'private' members of a class are either directly in
108 the C source file, or in files named asterisk/mod_*.h to make it clear
109 that they are not for inclusion by generic code.
111 Keep the number of header files small by not including them unnecessarily.
112 Don't cut&paste list of header files from other sources, but only include
113 those you really need. Apart from obvious cases (e.g. module.h which
114 is almost always necessary) write a short comment next to each #include to
115 explain why you need it.
118 * Declaration of functions and variables
119 ----------------------------------------
121 - Do not declare variables mid-block (e.g. like recent GNU compilers support)
122   since it is harder to read and not portable to GCC 2.95 and others.
124 - Functions and variables that are not intended to be used outside the module
125   must be declared static.
127 - When reading integer numeric input with scanf (or variants), do _NOT_ use '%i'
128   unless you specifically want to allow non-base-10 input; '%d' is always a better
129   choice, since it will not silently turn numbers with leading zeros into base-8.
131 - Strings that are coming from input should not be used as a first argument to
132   a formatted *printf function.
134 * Use the internal API
135 ----------------------
137 - Make sure you are aware of the string and data handling functions that exist
138   within Asterisk to enhance portability and in some cases to produce more
139   secure and thread-safe code. Check utils.c/utils.h for these.
141 - If you need to create a detached thread, use the ast_pthread_create_detached()
142   normally or ast_pthread_create_detached_background() for a thread with a smaller
143   stack size.  This reduces the replication of the code to handle the pthread_attr_t
144   structure.
146 * Code formatting
147 -----------------
149 Roughly, Asterisk code formatting guidelines are generally equivalent to the 
150 following:
152 # indent -i4 -ts4 -br -brs -cdw -lp -ce -nbfda -npcs -nprs -npsl -nbbo -saf -sai -saw -cs -l90 foo.c
154 this means in verbose:
155  -i4:    indent level 4
156  -ts4:   tab size 4
157  -br:    braces on if line
158  -brs:   braces on struct decl line
159  -cdw:   cuddle do while
160  -lp:    line up continuation below parenthesis
161  -ce:    cuddle else
162  -nbfda: dont break function decl args
163  -npcs:  no space after function call names
164  -nprs:  no space after parentheses
165  -npsl:  dont break procedure type
166  -saf:   space after for
167  -sai:   space after if
168  -saw:   space after while
169  -cs:    space after cast
170  -ln90:  line length 90 columns
172 Function calls and arguments should be spaced in a consistent way across
173 the codebase.
174         GOOD: foo(arg1, arg2);
175         BAD: foo(arg1,arg2);
176         BAD: foo (arg1, arg2);
177         BAD: foo( arg1, arg2 );
178         BAD: foo(arg1, arg2,arg3);
180 Don't treat keywords (if, while, do, return) as if they were functions;
181 leave space between the keyword and the expression used (if any). For 'return',
182 don't even put parentheses around the expression, since they are not
183 required.
185 There is no shortage of whitespace characters :-) Use them when they make
186 the code easier to read. For example:
188         for (str=foo;str;str=str->next)
190 is harder to read than
192         for (str = foo; str; str = str->next)
194 Following are examples of how code should be formatted.
196 - Functions:
197 int foo(int a, char *s)
199         return 0;
202 - If statements:
203 if (foo) {
204         bar();
205 } else {
206         blah();
209 - Case statements:
210 switch (foo) {
211 case BAR:
212         blah();
213         break;
214 case OTHER:
215         other();
216         break;
219 - No nested statements without braces, e.g.:
221 for (x = 0; x < 5; x++)
222         if (foo) 
223                 if (bar)
224                         baz();
226 instead do:
227 for (x = 0; x < 5; x++) {
228         if (foo) {
229                 if (bar) {
230                         baz();
231                 }
232         }
235 - Always use braces around the statements following an if/for/while construct,
236 even if not strictly necessary, as it reduces future possible problems.
238 - Don't build code like this:
240 if (foo) {
241         /* .... 50 lines of code ... */
242 } else {
243         result = 0;
244         return;
247 Instead, try to minimize the number of lines of code that need to be
248 indented, by only indenting the shortest case of the 'if'
249 statement, like so:
251 if (!foo) {
252         result = 0;
253         return;
256 .... 50 lines of code ....
258 When this technique is used properly, it makes functions much easier to read
259 and follow, especially those with more than one or two 'setup' operations
260 that must succeed for the rest of the function to be able to execute.
262 - Labels/goto are acceptable
263 Proper use of this technique may occasionally result in the need for a
264 label/goto combination so that error/failure conditions can exit the
265 function while still performing proper cleanup. This is not a bad thing!
266 Use of goto in this situation is encouraged, since it removes the need
267 for excess code indenting without requiring duplication of cleanup code.
268        
269 - Never use an uninitialized variable
270 Make sure you never use an uninitialized variable.  The compiler will 
271 usually warn you if you do so. However, do not go too far the other way,
272 and needlessly initialize variables that do not require it. If the first
273 time you use a variable in a function is to store a value there, then
274 initializing it at declaration is pointless, and will generate extra
275 object code and data in the resulting binary with no purpose. When in doubt,
276 trust the compiler to tell you when you need to initialize a variable;
277 if it does not warn you, initialization is not needed.
279 - Do not cast 'void *'
280 Do not explicitly cast 'void *' into any other type, nor should you cast any
281 other type into 'void *'. Implicit casts to/from 'void *' are explicitly
282 allowed by the C specification. This means the results of malloc(), calloc(),
283 alloca(), and similar functions do not _ever_ need to be cast to a specific
284 type, and when you are passing a pointer to (for example) a callback function
285 that accepts a 'void *' you do not need to cast into that type.
287 * Function naming
288 -----------------
290 All public functions (those not marked 'static'), must be named "ast_<something>"
291 and have a descriptive name.
293 As an example, suppose you wanted to take a local function "find_feature", defined
294 as static in a file, and used only in that file, and make it public, and use it
295 in other files. You will have to remove the "static" declaration and define a 
296 prototype in an appropriate header file (usually in include/asterisk). A more
297 specific name should be given, such as "ast_find_call_feature".
299 * Variable function argument parsing
300 ------------------------------------
302 Functions with a variable amount of arguments need a 'sentinel' when called.
303 Newer GNU C compilers are fine if you use NULL for this. Older versions (pre 4)
304 don't like this.
305 You should use the constant SENTINEL.
306 This one is defined in include/asterisk/compiler.h
308 * Variable naming
309 -----------------
311 - Global variables
312 Name global variables (or local variables when you have a lot of them or
313 are in a long function) something that will make sense to aliens who
314 find your code in 100 years.  All variable names should be in lower 
315 case, except when following external APIs or specifications that normally
316 use upper- or mixed-case variable names; in that situation, it is
317 preferable to follow the external API/specification for ease of
318 understanding.
320 Make some indication in the name of global variables which represent
321 options that they are in fact intended to be global.
322  e.g.: static char global_something[80]
324 - Don't use un-necessary typedef's
325 Don't use 'typedef' just to shorten the amount of typing; there is no substantial
326 benefit in this:
327 struct foo { int bar; }; typedef struct foo foo_t;
329 In fact, don't use 'variable type' suffixes at all; it's much preferable to
330 just type 'struct foo' rather than 'foo_s'.
332 - Use enums instead of #define where possible
333 Use enums rather than long lists of #define-d numeric constants when possible;
334 this allows structure members, local variables and function arguments to
335 be declared as using the enum's type. For example:
337 enum option {
338   OPT_FOO = 1,
339   OPT_BAR = 2,
340   OPT_BAZ = 4,
343 static enum option global_option;
345 static handle_option(const enum option opt)
347   ...
350 Note: The compiler will _not_ force you to pass an entry from the enum
351 as an argument to this function; this recommendation serves only to make
352 the code clearer and somewhat self-documenting. In addition, when using
353 switch/case blocks that switch on enum values, the compiler will warn
354 you if you forget to handle one or more of the enum values, which can be
355 handy.
357 * String handling
358 -----------------
360 Don't use strncpy for copying whole strings; it does not guarantee that the
361 output buffer will be null-terminated. Use ast_copy_string instead, which
362 is also slightly more efficient (and allows passing the actual buffer
363 size, which makes the code clearer).
365 Don't use ast_copy_string (or any length-limited copy function) for copying
366 fixed (known at compile time) strings into buffers, if the buffer is something
367 that has been allocated in the function doing the copying. In that case, you
368 know at the time you are writing the code whether the buffer is large enough
369 for the fixed string or not, and if it's not, your code won't work anyway!
370 Use strcpy() for this operation, or directly set the first two characters
371 of the buffer if you are just trying to store a one-character string in the
372 buffer. If you are trying to 'empty' the buffer, just store a single
373 NULL character ('\0') in the first byte of the buffer; nothing else is
374 needed, and any other method is wasteful.
376 In addition, if the previous operations in the function have already
377 determined that the buffer in use is adequately sized to hold the string
378 you wish to put into it (even if you did not allocate the buffer yourself),
379 use a direct strcpy(), as it can be inlined and optimized to simple
380 processor operations, unlike ast_copy_string().
382 * Use of functions
383 ------------------
385 When making applications, always ast_strdupa(data) to a local pointer if
386 you intend to parse the incoming data string.
388         if (data)
389                 mydata = ast_strdupa(data);
392 - Use the argument parsing macros to declare arguments and parse them, i.e.:
394         AST_DECLARE_APP_ARGS(args,
395                 AST_APP_ARG(arg1);
396                 AST_APP_ARG(arg2);
397                 AST_APP_ARG(arg3);
398         );
399         parse = ast_strdupa(data);
400         AST_STANDARD_APP_ARGS(args, parse);
402 - Create generic code!
403 If you do the same or a similar operation more than one time, make it a
404 function or macro.
406 Make sure you are not duplicating any functionality already found in an
407 API call somewhere.  If you are duplicating functionality found in 
408 another static function, consider the value of creating a new API call 
409 which can be shared.
411 * Handling of pointers and allocations
412 --------------------------------------
414 - Dereference or localize pointers
415 Always dereference or localize pointers to things that are not yours like
416 channel members in a channel that is not associated with the current 
417 thread and for which you do not have a lock.
418         channame = ast_strdupa(otherchan->name);
420 - Use const on pointer arguments if possible
421 Use const on pointer arguments which your function will not be modifying, as this 
422 allows the compiler to make certain optimizations. In general, use 'const'
423 on any argument that you have no direct intention of modifying, as it can
424 catch logic/typing errors in your code when you use the argument variable
425 in a way that you did not intend.
427 - Do not create your own linked list code - reuse!
428 As a common example of this point, make an effort to use the lockable
429 linked-list macros found in include/asterisk/linkedlists.h. They are
430 efficient, easy to use and provide every operation that should be
431 necessary for managing a singly-linked list (if something is missing,
432 let us know!). Just because you see other open-coded list implementations
433 in the source tree is no reason to continue making new copies of
434 that code... There are also a number of common string manipulation
435 and timeval manipulation functions in asterisk/strings.h and asterisk/time.h;
436 use them when possible.
438 - Avoid needless allocations!
439 Avoid needless malloc(), strdup() calls. If you only need the value in
440 the scope of your function try ast_strdupa() or declare structs on the
441 stack and pass a pointer to them. However, be careful to _never_ call
442 alloca(), ast_strdupa() or similar functions in the argument list
443 of a function you are calling; this can cause very strange stack
444 arrangements and produce unexpected behavior.
446 -Allocations for structures
447 When allocating/zeroing memory for a structure, use code like this:
449 struct foo *tmp;
453 tmp = ast_calloc(1, sizeof(*tmp));
455 Avoid the combination of ast_malloc() and memset().  Instead, always use
456 ast_calloc(). This will allocate and zero the memory in a single operation. 
457 In the case that uninitialized memory is acceptable, there should be a comment
458 in the code that states why this is the case.
460 Using sizeof(*tmp) instead of sizeof(struct foo) eliminates duplication of the 
461 'struct foo' identifier, which makes the code easier to read and also ensures 
462 that if it is copy-and-pasted it won't require as much editing.
464 The ast_* family of functions for memory allocation are functionally the same.
465 They just add an Asterisk log error message in the case that the allocation
466 fails for some reason. This eliminates the need to generate custom messages
467 throughout the code to log that this has occurred.
469 -String Duplications
471 The functions strdup and strndup can *not* accept a NULL argument. This results
472 in having code like this:
474         if (str)
475                 newstr = strdup(str);
476         else
477                 newstr = NULL;
479 However, the ast_strdup and ast_strdupa functions will happily accept a NULL
480 argument without generating an error.  The same code can be written as:
481         
482         newstr = ast_strdup(str);
484 Furthermore, it is unnecessary to have code that malloc/calloc's for the length
485 of a string (+1 for the terminating '\0') and then using strncpy to copy the
486 copy the string into the resulting buffer.  This is the exact same thing as
487 using ast_strdup.
489 * CLI Commands
490 --------------
492 New CLI commands should be named using the module's name, followed by a verb
493 and then any parameters that the command needs. For example:
495 *CLI> iax2 show peer <peername>
499 *CLI> show iax2 peer <peername>
501 * New dialplan applications/functions
502 -------------------------------------
504 There are two methods of adding functionality to the Asterisk
505 dialplan: applications and functions. Applications (found generally in
506 the apps/ directory) should be collections of code that interact with
507 a channel and/or user in some significant way. Functions (which can be
508 provided by any type of module) are used when the provided
509 functionality is simple... getting/retrieving a value, for
510 example. Functions should also be used when the operation is in no way
511 related to a channel (a computation or string operation, for example).
513 Applications are registered and invoked using the
514 ast_register_application function; see the apps/app_skel.c file for an
515 example.
517 Functions are registered using 'struct ast_custom_function'
518 structures and the ast_custom_function_register function.
520 * Doxygen API Documentation Guidelines
521 --------------------------------------
523 When writing Asterisk API documentation the following format should be
524 followed. Do not use the javadoc style.
527  * \brief Do interesting stuff.
529  * \param thing1 interesting parameter 1.
530  * \param thing2 interesting parameter 2.
532  * This function does some interesting stuff.
534  * \retval zero on success
535  * \retval -1 on error.
536  */
537 int ast_interesting_stuff(int thing1, int thing2)
539         return 0;
542 Notice the use of the \param, \brief, and \return constructs.  These should be
543 used to describe the corresponding pieces of the function being documented.
544 Also notice the blank line after the last \param directive.  All doxygen
545 comments must be in one /*! */ block.  If the function or struct does not need
546 an extended description it can be left out.
548 Please make sure to review the doxygen manual and make liberal use of the \a,
549 \code, \c, \b, \note, \li and \e modifiers as appropriate.
551 When documenting a 'static' function or an internal structure in a module,
552 use the \internal modifier to ensure that the resulting documentation
553 explicitly says 'for internal use only'.
555 Structures should be documented as follows.
558  * \brief A very interesting structure.
559  */
560 struct interesting_struct
562         /*! \brief A data member. */
563         int member1;
565         int member2; /*!< \brief Another data member. */
568 Note that /*! */ blocks document the construct immediately following them
569 unless they are written, /*!< */, in which case they document the construct
570 preceding them.
572 It is very much preferred that documentation is not done inline, as done in
573 the previous example for member2.  The first reason for this is that it tends
574 to encourage extremely brief, and often pointless, documentation since people
575 try to keep the comment from making the line extremely long.  However, if you
576 insist on using inline comments, please indent the documentation with spaces!
577 That way, all of the comments are properly aligned, regardless of what tab
578 size is being used for viewing the code.
580 * Finishing up before you submit your code
581 ------------------------------------------
583 - Look at the code once more
584 When you achieve your desired functionality, make another few refactor
585 passes over the code to optimize it.
587 - Read the patch
588 Before submitting a patch, *read* the actual patch file to be sure that 
589 all the changes you expect to be there are, and that there are no 
590 surprising changes you did not expect. During your development, that
591 part of Asterisk may have changed, so make sure you compare with the
592 latest CVS.
594 - Listen to advice
595 If you are asked to make changes to your patch, there is a good chance
596 the changes will introduce bugs, check it even more at this stage.
597 Also remember that the bug marshal or co-developer that adds comments 
598 is only human, they may be in error :-)
600 - Optimize, optimize, optimize
601 If you are going to reuse a computed value, save it in a variable
602 instead of recomputing it over and over.  This can prevent you from 
603 making a mistake in subsequent computations, making it easier to correct
604 if the formula has an error and may or may not help optimization but 
605 will at least help readability.
607 Just an example (so don't over analyze it, that'd be a shame):
609 const char *prefix = "pre";     
610 const char *postfix = "post";
611 char *newname;
612 char *name = "data";
614 if (name && (newname = alloca(strlen(name) + strlen(prefix) + strlen(postfix) + 3)))
615         snprintf(newname, strlen(name) + strlen(prefix) + strlen(postfix) + 3, "%s/%s/%s", prefix, name, postfix);
617 ...vs this alternative:
619 const char *prefix = "pre";
620 const char *postfix = "post";
621 char *newname;
622 char *name = "data";
623 int len = 0;
625 if (name && (len = strlen(name) + strlen(prefix) + strlen(postfix) + 3) && (newname = alloca(len)))
626         snprintf(newname, len, "%s/%s/%s", prefix, name, postfix);
628 * Creating new manager events?
629 ------------------------------
630 If you create new AMI events, please read manager.txt. Do not re-use
631 existing headers for new purposes, but please re-use existing headers
632 for the same type of data.
634 Manager events that signal a status are required to have one
635 event name, with a status header that shows the status.
636 The old style, with one event named "ThisEventOn" and another named
637 "ThisEventOff", is no longer approved.
639 Check manager.txt for more information on manager and existing
640 headers. Please update this file if you add new headers.
642 * Locking in Asterisk
643 -----------------------------
645 A) Locking Fundamentals
647 Asterisk is a heavily multithreaded application.  It makes extensive
648 use of locking to ensure safe access to shared resources between
649 different threads.
651 When more that one lock is involved in a given code path, there is the
652 potential for deadlocks.  A deadlock occurs when a thread is stuck
653 waiting for a resource that it will never acquire.  Here is a classic
654 example of a deadlock:
656    Thread 1                   Thread 2
657    ------------               ------------
658    Holds Lock A               Holds Lock B
659    Waiting for Lock B         Waiting for Lock A
661 In this case, there is a deadlock between threads 1 and 2.
662 This deadlock would have been avoided if both threads had
663 agreed that one must acquire Lock A before Lock B.
665 In general, the fundamental rule for dealing with multiple locks is
667     an order _must_ be established to acquire locks, and then all threads
668     must respect that order when acquiring locks.
671 A.1) Establishing a locking order
673 Because any ordering for acquiring locks is ok, one could establish
674 the rule arbitrarily, e.g. ordering by address, or by some other criterion.
675 The main issue, though, is defining an order that
676   i) is easy to check at runtime;
677   ii) reflects the order in which the code executes.
678 As an example, if a data structure B is only accessible through a
679 data structure A, and both require locking, then the natural order
680 is locking first A and then B.
681 As another example, if we have some unrelated data structures to
682 be locked in pairs, then a possible order can be based on the address
683 of the data structures themselves.
685 B) Minding the boundary between channel drivers and the Asterisk core
687 The #1 cause of deadlocks in Asterisk is by not properly following the
688 locking rules that exist at the boundary between Channel Drivers and
689 the Asterisk core.  The Asterisk core allocates an ast_channel, and
690 Channel Drivers allocate "technology specific private data" (PVT) that is
691 associated with an ast_channel.  Typically, both the ast_channel and
692 PVT have their own lock.  There are _many_
693 code paths that require both objects to be locked.
695 The locking order in this situation is the following:
697     1) ast_channel
698     2) PVT
700 Channel Drivers implement the ast_channel_tech interface to provide a
701 channel implementation for Asterisk.  Most of the channel_tech
702 interface callbacks are called with the associated ast_channel
703 locked.  When accessing technology specific data, the PVT can be locked
704 directly because the locking order is respected.
706 C) Preventing lock ordering reversals.
708 There are some code paths which make it extremely difficult to
709 respect the locking order.
710 Consider for example the following situation:
712     1) A message comes in over the "network"
713     2) The Channel Driver (CD) monitor thread receives the message
714     3) The CD associates the message with a PVT and locks the PVT
715     4) While processing the message, the CD must do something that requires
716        locking the ast_channel associated to the PVT
718 This is the point that must be handled carefully.
719 The following psuedo-code
721       unlock(pvt);
722       lock(ast_channel);
723       lock(pvt);
725 is _not_ correct for two reasons:
727 i) first and foremost, unlocking the PVT means that other threads
728    can acquire the lock and believe it is safe to modify the
729    associated data. When reacquiring the lock, the original thread
730    might find unexpected changes in the protected data structures.
731    This essentially means that the original thread must behave as if
732    the lock on the pvt was not held, in which case it could have
733    released it itself altogether;
735 ii) Asterisk uses the so called "recursive" locks, which allow a thread
736    to issue a lock() call multiple times on the same lock. Recursive
737    locks count the number of calls, and they require an equivalent
738    number of unlock() to be actually released.
740    For this reason, just calling unlock() once does not guarantee that the
741    lock is actually released -- it all depends on how many times lock()
742    was called before.
744 An alternative, but still incorrect, construct is widely used in
745 the asterisk code to try and improve the situation:
747       while (trylock(ast_channel) == FAILURE) {
748           unlock(pvt);
749           usleep(1); /* yield to other threads */
750           lock(pvt);
751       }
753 Here the trylock() is non blocking, so we do not deadlock if the ast_channel
754 is already locked by someone else: in this case, we try to unlock the PVT
755 (which happens only if the PVT lock counter is 1), yield the CPU to
756 give other threads a chance to run, and then acquire the lock again.
758 This code is not correct for two reasons:
759   i) same as in the previous example, it releases the lock when the thread
760      probably did not expect it;
761   ii) if the PVT lock counter is greater than 1 we will not
762      really release the lock on the PVT. We might be lucky and have the
763      other contender actually release the lock itself, and so we will "win"
764      the race, but if both contenders have their lock counts > 1 then
765      they will loop forever (basically replacing deadlock with livelock).
767 Another variant of this code is the following:
769     if (trylock(ast_channel) == FAILURE) {
770         unlock(pvt);
771         lock(ast_channel);
772         lock(pvt);
773     }
775 which has the same issues as the while(trylock...) code, but just
776 deadlocks instead of looping forever in case of lock counts > 1.
778 The deadlock/livelock could be in principle spared if one had an
779 unlock_all() function that calls unlock as many times as needed to
780 actually release the lock, and reports the count. Then we could do:
782     if (trylock(ast_channel) == FAILURE) {
783         n = unlock_all(pvt);
784         lock(ast_channel)
785         while (n-- > 0) lock(pvt);
786     }
788 The issue with unexpected unlocks remains, though.
790 C) Locking multiple channels.
792 The next situation to consider is what to do when you need a lock on
793 multiple ast_channels (or multiple unrelated data structures).
795 If we are sure that we do not hold any of these locks, then the
796 following construct is sufficient:
798          lock(MIN(chan1, chan2));
799          lock(MAX(chan1, chan2));
801 That type of code would follow an established locking order of always
802 locking the channel that has a lower address first.  Also keep in mind
803 that to use this construct for channel locking, one would have to go
804 through the entire codebase to ensure that when two channels are locked,
805 this locking order is used.
806    However, if we enter the above section of code with some lock held
807 (which would be incorrect using non-recursive locks, but is completely
808 legal using recursive mutexes) then the locking order is not guaranteed
809 anymore because it depends on which locks we already hold. So we have
810 to go through the same tricks used for the channel+PVT case.
812 D) Recommendations
814 As you can see from the above discussion, getting locking right is all
815 but easy. So please follow these recommendations when using locks:
817 *) Use locks only when really necessary
818     Please try to use locks only when strictly necessary, and only for
819     the minimum amount of time required to run critical sections of code.
820     A common use of locks in the current code is to protect a data structure
821     from being released while you use it.
822     With the use of reference-counted objects (astobj2) this should not be
823     necessary anymore.
825 *) Do not sleep while holding a lock
826     If possible, do not run any blocking code while holding a lock,
827     because you will also block other threads trying to access the same
828     lock. In many cases, you can hold a reference to the object to avoid
829     that it is deleted while you sleep, perhaps set a flag in the object
830     itself to report other threads that you have some pending work to
831     complete, then release and acquire the lock around the blocking path,
832     checking the status of the object after you acquire the lock to make
833     sure that you can still perform the operation you wanted to.
835 *) Try not to exploit the 'recursive' feature of locks.
836     Recursive locks are very convenient when coding, as you don't have to
837     worry, when entering a section of code, whether or not you already
838     hold the lock -- you can just protect the section with a lock/unlock
839     pair and let the lock counter track things for you.
840        But as you have seen, exploiting the features of recursive locks
841     make it a lot harder to implement proper deadlock avoidance strategies.
842     So please try to analyse your code and determine statically whether you
843     already hold a lock when entering a section of code.
844        If you need to call some function foo() with and without a lock held,
845     you could define two function as below:
846         foo_locked(...) {
847             ... do something, assume lock held
848         }
850         foo(...) {
851             lock(xyz)
852             ret = foo_locked(...)
853             unlock(xyz)
854             return ret;
855         }
856     and call them according to the needs.
858 *) Document locking rules.
859     Please document the locking order rules are documented for every
860     lock introduced into Asterisk.  This is done almost nowhere in the
861     existing code.  However, it will be expected to be there for newly
862     introduced code.  Over time, this information should be added for
863     all of the existing lock usage.
865 -----------------------------------------------------------------------
868             ------------------------------------
869             ==  PART TWO: BUILD ARCHITECTURE  ==
870             ------------------------------------
872 The asterisk build architecture relies on autoconf to detect the
873 system configuration, and on a locally developed tool (menuselect) to
874 select build options and modules list, and on gmake to do the build.
876 The first step, usually to be done soon after a checkout, is running
877 "./configure", which will store its findings in two files:
879     + include/asterisk/autoconfig.h
880         contains C macros, normally #define HAVE_FOO or HAVE_FOO_H ,
881         for all functions and headers that have been detected at build time.
882         These are meant to be used by C or C++ source files.
884     + makeopts
885         contains variables that can be used by Makefiles.
886         In addition to the usual CC, LD, ... variables pointing to
887         the various build tools, and prefix, includedir ... which are
888         useful for generic compiler flags, there are variables
889         for each package detected.
890         These are normally of the form FOO_INCLUDE=... FOO_LIB=...
891         FOO_DIR=... indicating, for each package, the useful libraries
892         and header files. 
894 The next step is to run "make menuselect", to extract the dependencies existing
895 between files and modules, and to store build options.
896 menuselect produces two files, both to be read by the Makefile:
898     + menuselect.makeopts
899         Contains for each subdirectory a list of modules that must be
900         excluded from the build, plus some additional informatiom.
901     + menuselect.makedeps
902         Contains, for each module, a list of packages it depends on.
903         For each of these packages, we can collect the relevant INCLUDE
904         and LIB files from makeopts. This file is based on information
905         in the .c source code files for each module.
907 The top level Makefile is in charge of setting up the build environment,
908 creating header files with build options, and recursively invoking the
909 subdir Makefiles to produce modules and the main executable.
911 The sources are split in multiple directories, more or less divided by
912 module type (apps/ channels/ funcs/ res/ ...) or by function, for the main
913 binary (main/ pbx/).
916 TO BE COMPLETED
918     
919 -----------------------------------------------
920 Welcome to the Asterisk development community!
921 Meet you on the asterisk-dev mailing list. 
922 Subscribe at http://lists.digium.com!
924 -- The Asterisk.org Development Team