System Architecture Group Department of Science

Study Thesis

Implementation of Flow Control in the Stack BlueZ

by cand. inform. Martin Röhricht

Supervisor: Prof. Dr. Frank Bellosa Dr. Thomas Fuhrmann

Hiermit erkläre ich, die vorliegende Arbeit selbständig verfasst und keine anderen als die angegebenen Literaturhilfsmittel verwendet zu haben.

I hereby declare that this thesis is a work of my own, and that only cited sources have been used.

Karlsruhe, October 01, 2006

...... Martin Röhricht

Acknowledgements

I would like to thank my supervisor Dr. Thomas Fuhrmann and Prof. Dr. Frank Bellosa who gave me the opportunity to work on the in a real life uni- versity’s project. Furthermore I would like to thank the maintainer of the Bluetooth subsystem in the Linux kernel, Marcel Holtmann, as well as my fellow students Jo- hannes Singler and Christoph Mallon for the help they provided me during my first steps and setups. This work could have never been accomplished without the invaluable support of my parents and my girlfriend Karin. Thank you so much.

Contents

1. Introduction 4 1.1. The Bluetooth Protocol Stack ...... 5 1.2. The Logical Link Control and Adaptation Protocol (L2CAP) ...... 5 1.2.1. Terminology ...... 8 1.3. Related Work ...... 8 2. Linux Kernel Development 9 2.1. Socket Buffers ...... 9 2.1.1. Lists of Socket Buffers ...... 11 2.2. Portability ...... 12 2.2.1. Alignment and Endianess ...... 13 2.2.2. Concurrency and Race Conditions ...... 14 3. Conguration Process 16 3.1. Information Retrieval ...... 16 3.1.1. Information Request ...... 16 3.1.2. Information Response ...... 16 3.1.3. Extended Features Mask ...... 17 3.2. Configuration Request ...... 18 3.3. Configuration Response ...... 20 3.4. Retransmission and Flow Control Option ...... 21 4. Procedures for Flow Control 24 4.1. Variables and Sequence Numbers ...... 27 4.1.1. The sending peer ...... 27 4.1.2. The receiving peer ...... 28 4.2. Retrieving Data ...... 29 4.2.1. Invalid Frame Detection ...... 29 4.2.2. Process the Send Sequence Number TxSeq ...... 30 4.2.3. Process the Receive Sequence Number ReqSeq ...... 30 4.2.4. Reassemble the SDU ...... 31 4.3. Transmitting Data ...... 33 4.3.1. Sending Acknowledgments ...... 35 4.3.2. Monitor and Retransmission Timer ...... 36

1 Contents

5. Summary 38 5.1. Testing and Analysis ...... 38 5.2. Conclusion and Future Work ...... 40 A. Architectures' Data Types 41

B. Development Notes 42 B.1. Bluetooth Adapters Used ...... 43

2 iu’ButohsbytmBlueZ. subsystem an Bluetooth Linux Linux’ makes costs no by available freely and platform. development source ideal soft- open Bluetooth being proprietary but existing many stacks, so ware to BlueZ. called equivalent stack, the is Bluetooth implementation the This of implementation existing an users its fers to buffers their provides for instead overflows. values control buffer appropriate Flow from negotiate buffer. them incom- to its protect the into devices process with passed enable to device is that able data remote not mechanisms, new is the device than con- flooding receiving faster flow devices the data that prevent is ing quickly, so to extensions sent meant these is is that of data, mode One This (SIG). specified Group being mode. service Interest point trol of Special technical quality some Bluetooth a see from the to data companies by for receiving well. urgent as and became rised, it sending view, tasks of of different fulfill functionality to basic hardware needs the With the small standard Besides phone. this mobile on Bluetooth and of protocols laptop laid acceptance design. new rising transport was every the space-saving almost data focus a in nowadays digital and The included major are consumption adapters the power devices. low of embedded costs, one and development as small used for be mainly to going is Bluetooth Summary Executive hstei saota mlmnaino lwCnrli h 2A ae for layer L2CAP the in Control Flow of implementation an about is thesis This of- system, operating GNU/Linux the of heart the builds which kernel, Linux The 3

0 1. Introduction

The Bluetooth technology was developed by Ericsson, , Intel, IBM and in the mid-1990’s. These companies built the core of the Bluetooth Special Interest Group (SIG) which serves as an official consortium and is composed of 6123 members in the meantime.1 The Bluetooth wireless technology is focused mainly on short-range communica- tion and domain-specific applications. Because of its low energy consumption and low costs it perfectly fits the needs of small embedded devices such as Notebooks, PDAs or mobile phones. The official Bluetooth website bluetooth.com describes the technology as follows: “Bluetooth wireless technology is a short-range communications tech- nology intended to replace the cables connecting portable and/or fixed devices while maintaining high levels of security. The key features of Blue- tooth technology are robustness, low power, and low cost.”2 The domain specific applications—also known as Profiles—build a characteristical foundation of the technology which distinguishes it from most other wireless tech- nologies. Instead of just specifying the core technical parts, the Bluetooth specifi- cation defines some core profiles for which the technology is meant to be used and which may be supported by Bluetooth compliant devices. Currently there are 33 unique profiles defined (e.g. Audio/Video Remote Control Profile (AVRCP), Basic Imaging Profile (BIP), Basic Printing Profile (BPP), Bluetooth Network Encapsulation Protocol (BNEP), Dial-up Networking Profile (DUN), Fax Profile (FAX), File Transfer Profile (FTP), Profile (HID), Object Exchange (OBEX), Per- sonal Area Networking Profile (PAN), Radio Frequency Communication (RFCOMM) or Service Discovery Protocol (SDP)).3 The use of fixed, defined profiles enables companies to guarantee specific interop- erability by fulfilling the corresponding qualification processes. This is an advantage in the low end sector of embedded devices [see also Wollert, 2002, page 27].

1This statistics arise from September 2006. The membership is separated into Promoter Members (8 companies), Associate Members (231) and Adopter Members (5884)—only the latter one is free of charge. The Promoter Members consist of the founder companies (with Lenovo (Singapore) Pte Ltd. instead of IBM) plus Agere Systems, Microsoft Corporation and , Inc. 2See http://www.bluetooth.com/Bluetooth/Learn/Basics/ (last visit 27 Sep 2006) 3For a complete list with short explanations refer to http://bluetooth.com/Bluetooth/Learn/ Works/Profiles_Overview.htm (last visit 27 Sep 2006)

4 0 oe,s htButohbcm nonIE tnad802.15. standard IEEE own an own became its Bluetooth into that technology so Bluetooth model, core [see 802 the model mapped TCP/IP committee the standardization to IEEE applicable it figure is (see nor coupled stack loosely Bluetooth into separated The are which layers. protocols many has standard Bluetooth Stack The Protocol Bluetooth The 1.1. stated. aesadteLCPlyr ec rfie r mlmne ihnteuprlayers. upper the within lower implemented the are also between profiles [see bridge Hence the layer. L2CAP builds soft- the (HCI) separated and Interface a layers Controller in controller’s Host implemented the The are layers within stack. and ware layers protocols protocol level lower higher The the firmware. only provide devices Bluetooth All Adaptation and Control Link Logical The 1.2. iue ihnti etaetknfo h fca pcfiaini o otherwise not if specification official the from taken are text this within Figures h 2A ae a he anfunctions: main three has layer L2CAP The rtcl(L2CAP) Protocol Wollert O B X E Audio , 2002 iue1.1.: Figure TCP/IP hpe 4]. Chapter , PPP RFCOMM vriwo h leot Stack Bluetooth the of Overview leot Radio Bluetooth Commands Application Baseband L2CAP AT 1.1 ikManager Link osnihrflo h S/S model, ISO/OSI the follow neither does ) Tanenbaum ..TeButohPooo Stack Protocol Bluetooth The 1.1. TCS , 2003 SDP hpe ..] The 4.6.3]. Chapter , HCI 5

1 1. Introduction

1. L2CAP accepts frames with up to 64KB of length. Applications may usually require to send data packets that exceed this limitation, whereas the baseband on the other hand has an even more intense constraint towards smaller frame sizes. This forces the L2CAP layer to segment big data packets into smaller frames on the sending side, and to reassemble frames on the receiving side.

2. Higher level protocol multiplexing. Due to the lack of an appropriate type field in the lower layers identifying higher level protocols it is L2CAP’s responsibility to distinguish protocols such as RFCOMM, SDP, or Telephony Control on its own.

3. L2CAP is responsible for all parts of Quality of Service. This includes the con- nection setup as well as necessary negotiations regarding sending and receiving parameters and aspects like flow control and retransmission. L2CAP supports connection-oriented data services as well as connectionless ones for higher layer protocols. The concept is based on per-connection channels which provides the ability to transfer multiple protocols over one asynchroneous link si- multaneously. Figure 1.2 gives an overview of the internal L2CAP architectural block as described by the specificaton. The Channel Manager is responsible for all kinds of signalling. It provides the control functionality and manages signals to and from the lower layers, the upper layers and the Resource Manager. The Retransmission and Flow Control part is located within the Resource Manager. This block may provide applications per-channel flow control and retransmission. The Resource Manager is responsible for all transmission and reception activities of packets related to L2CAP channels. Some core parts of the L2CAP layer are to be explained in more detail. Segmentation and Reassembly This technique takes place between the upper layer protocols that are directly related to applications (like TCP/IP or RFCOMM) and the L2CAP layer. The data packet that is exchanged between those layers is called a Service Data Unit (SDU) with the Maximum Transmission Unit (MTU) as its maximum size. The application is totally decoupled from the required seg- mentation that needs to be done to map the application packets into the lower layer frames.

Flow Control per channel L2CAP offers the optional feature of per-channel Flow Control which is the base of this work. Providing this technique within a pro- tocol layer for all tasks prevents applications from being forced to implement it on their own. Instead of a simple stop-and-go Flow Control scheme as em- ployed in the baseband, a more efficient window-based Flow Control scheme is provided. This feature is an optional part of the specification.

Error Control and Retransmission An extra error checking mechanism within the L2CAP layer is provided for applications that require a lower error rate than the baseband can deliver. An error check (based on a CRC checksum) is used in

6 rgetto n Recombination and Fragmentation osdrdls,a ela idwbsdflwcnrlmcaimcnb accom- thesis be this which can on mechanism option are control control based. that flow flow is and frames based retransmission window retransmit new L2CAP’s a to by as and plished well acknowledgements as send se- lost, byte check to considered frame the ability and splitting numbers The by sequence connection using reliable quences. and a frames) (named specifica- of blocks Bluetooth insurance the into the of stream include one the parts to Those strictly compared tion. be cannot stack ISO/OSI the if 2A mlmnsmjrprso h aaln ae fteIOOImdl even model, ISO/OSI the of layer link data the of parts major implements L2CAP tef ri tocr nteHIdie,ado nteCnrle.Fragmentation layer. Controller. L2CAP the BlueZ the in of and/or driver, part not HCI layer is the leaves L2CAP recombination the in specification and of occurs part the it is ensure procedure if that this or techniques if Note itself, implementation Both actual layer. the to lower open recombination. it the called fragmenta- with called is collaboration is operation proper fragments reverse smaller the into PDUs tion; layer Splitting which upper optional (PDUs) the data. Units besides information information Data protocol Protocol L2CAP entire using the by contain performed is Interface Controller loss. packet from device the protecting by connection reliable mode Retransmission a optional provide The shall mode. Control Flow and Retransmission the iue1.2.: Figure

2A rhtcua lc [see block architectural L2CAP ..TeLgclLn oto n dpainPooo (L2CAP) Protocol Adaptation and Control Link Logical The 1.2.

daØa xhnigdt ewe 2A n h Host the and L2CAP between data Exchanging daØa daØa BlueSpec o.4pg 22] page 4 Vol. , 7

1 1. Introduction

1.2.1. Terminology

It is indeed important to keep the terminology in mind. The SDU (Service Data Unit) is the data packet that is to be exchanged between the L2CAP layer and the upper layers (refer to figure 1.2). The SDU is the plain data unit that is received by L2CAP from the upper layer and does not contain any L2CAP specific header information. Therefore the techniques applied to SDUs are called segmentation and reassembly. Instead, the PDU (Protocol Data Unit) is the data packet containing L2CAP specific protocol information, control information and/or upper layer information data and is always preceeded by an L2CAP header. The PDU can be of types B-frame, C-frame, G-frame, I-frame and S-frame—the latter two are used within Flow Control mode, the first one (B-frame) is used in basic L2CAP mode. Fragments are used in the delivery of data to and from the lower layer. Therefore the corresponding actions applied to fragment PDUs are called fragmentation and recombination. The MTU (Maximum Transmission Unit) describes the maximum size of payload data that can be exchanged between the L2CAP layer and the upper layer entity—this corresponds to the maximum SDU size respectively. The MPS (Maximum PDU Payload Size) on the other hand corresponds to the size that the L2CAP layer entity is capable of accepting from the lower layer entity. Note that either in Basic L2CAP mode, or if no segmentation is used in Flow Control mode, the MTU equals the MPS.

1.3. Related Work

Multiple Bluetooth stacks are widely used. Especially for the op- erating system exist several different proprietary Bluetooth stacks albeit none of them is open source. Besides the other common open source BSD implementations there are two Bluetooth stack implementations for Linux which are both released under the terms of the General Public License (GPL). One of them is called AFFIX4 and was primarily developed by Nokia. This stack is totaly independent of the currently used official stack BlueZ on which this thesis is based. AFFIX already implements some parts of the newly introduced features of the Bluetooth specification 1.2, e.g. Retrans- mission and Flow Control. Further development of this stack slowed down during the past years—only security patches were introduced since the last major release 3.2.0 in July 2004.

4http://affix.sourceforge.net

8 napiainnest eddt (via data send to needs application (via thesis. an reception this frame of work of the case is in in structure involved This not is block. but data data the paged about transfer information to used additional mainly keep to used is which needs. layer’s each to adjusted be the of this of diagram makes main protocols The different figure variables. all in of by shown number is tremendous and structure a layers with different structure all huge by a used it is it As transmitted. [ to refer macros discussion and detailed functions 2]. more the Chapter a of For some fields. over those go and manipulate we detail that for why in that’s information structure self-explanatory, data not further this are discuss with fields will the and along all of abstract structure stored Some an data coordination. are in this internal payload some Within lies information use layers. the main network and different Its headers all kernel. for Linux storage the packet in generic code networking all within structure buffer socket The Buers Socket 2.1. [ finally kernel. and the of development internals driver’s networking device the Linux of purpose the [ kernel, Linux for the essential of [ are explanation design, [ which and are aspects implementation regard these development kernel’s this of the the in some Helpful of cover developer. now parts kernel will specific We any of whole. understanding a some as solid involves process a GNU/Linux like and system knowledge operating an deeper of kernel the inside Developing Development Kernel Linux 2. ufr rcsl otefis yeatrtedt eto.Ti one a eadjusted. be may pointer This section. data the after byte The first the to precisely buffer, The afterwards. adjusted be never is and time tion okn ihnteLCPlyrmasw s narayalctdsce buffer socket allocated already an use we means layer L2CAP the within Working The The end data sk_buff head one onst h einn fteso-called the of beginning the to points pointer hc ossso edr n h nomto ala.Ti one can pointer This payload. information the and headers of consists which one onst h rtbt hti eundb mlo tbfe alloca- buffer at kmalloc by returned is that byte first the to points pointer tutr ersnshaesfrdt hthsbe eevdo st be to is or received been has that data for headers represents structure 2.1 sk_buff . l2cap_data_channel() obte al. et Corbet tail saciia aasrcueta sue widely used is that structure data critical a is onst h n ftedt eto ihnthe within section data the of end the to points l2cap_sock_sendmsg() oe n Cesati and Bovet , 2005 Love data n [ and ] u aet loaemmr if memory allocate to have but ) , one eun h beginning the returns pointer 2005 ud n Kunst and Quade skb_shared_info , .Mmr loainfor allocation Memory ). 2006 o odoeve of overview good a for ] Benvenuti o eydetailed very a for ] Benvenuti , , structure 2006 2006 , 2006 for ] for ] 9 ,

2 2. Linux Kernel Development

struct skb_buff *skb - ··· head headroom - data 6 tail end ··· DATA skb->len Buffer

- ? tailroom -

Figure 2.1.: The sk_buff struct and their head/end versus data/tail pointers socket buffers is done in BlueZ by using bt_skb_send_alloc(). After that we make use of three different management functions. Note that none of these functions actually copies data from or into the buffer—only pointers are adjusted accordingly.

• skb_put extends the tail pointer by a given length, increases the len field and returns the old position of the tail pointer. This is a major function used when- ever we copy some data into the socket buffer e.g.: memcpy(skb_put(l2cap_pi(sk)->sdu, skb->len), skb->data, skb ->len);

or if we reserve some space for a given struct, e.g. /* Create L2CAP header */ lh = (struct l2cap_hdr *) skb_put(skb, L2CAP_HDR_SIZE); lh->cid = __cpu_to_le16(l2cap_pi(sk)->dcid); lh->len = __cpu_to_le16(len + (hlen - L2CAP_HDR_SIZE));

• skb_pull is used to pull the data pointer towards the tail by a given length and returns the new data pointer; the len field is decreased respectively. This can be used to remove data from the front of a buffer and is widely used in each layer to remove the layer’s header from the packet.

• skb_trim trims the socket buffer to a given length and moves the tail pointer towards the head. This function is useful if we want to cut a trailer off the packet like a given frame check sequence.

10 osoemr hnoecrepnigsce ufr ocle oktbfe list buffer socket so-called a buffer, socket corresponding one ( than more store Buers To Socket of Lists 2.1.1. tefis w lmnso both of elements two first “the and list this on where list packets linked doubly a follows implementation The n alomi o eaddadmyo a o efildwt data. with filled be not may or may and regarded not is tailroom and within combination in used are functions two latter The tutsk_buff_head struct Figure tutsbbf *skb skb_buff struct }; *rmv edr,cnrladfsfo -fae*/ frame i- from fcs and control , header remove /* tuts_ufha { sk_buff_head struct k_rm(k k >ln-LCPFSSZ ); ); L2CAP_FCS_SIZE L2CAP_CONTROL_SIZE - + len -> skb , (skb L2CAP_HDR_SIZE skb_trim , (skb skb_pull iue2.2.: Figure 2.2 lutae o nIfaei trdwti oktbfe.Teheadroom The buffer. socket a within stored is I-frame an how illustrates head data end tail · · · · · · *Teetommesms efrt.*/ . first be must members two These /* _3 ln; qlen __u32 tuts_uf*pe ; prev * ; next * sk_buff struct sk_buff struct pnoktlc ; lock spinlock_t The sue.Tedfiiini ut simple: quite is definition The used. is ) sk_buff lock a eue o nSPaaelcigplc.Nt that Note policy. locking SMP-aware an for used be can tutwt h -rmsfil ntedt section data the in field I-frames the with struct sk_buff and - - - - sk_buff_head Buffer DATA headroom qlen tailroom l2cap_reassembly() r h ae h etand next the same: the are ersnstenme of number the represents D length SDU Information ..Sce Buffers Socket 2.1. Payload Control Length FCS CID : skb->len 6 ? 11

2 2. Linux Kernel Development prev pointers. This allows the two structures to coexist in the same list. [. . . ] In addi- tion, the same functions can be used to manipulate both sk_buff and sk_buff_head.” [Benvenuti, 2006] Such a list was introduced by this implementation for the transmission TxQueue in l2cap.h. The functions and macros to manipulate these lists are straight forward. Three of them are used within this implementation:

• skb_queue_head_init is an initialization function for a sk_buff_head object.

• skb_queue_tail puts a socket buffer at the tail of a list.

• skb_dequeue removes a socket buffer from the head of the queue and returns it. If the list is empty NULL is returned respectively.

Some more information about how socket buffers work can be found online on Dave M. Miller’s web pages: http://vger.kernel.org/~davem/skb.html

2.2. Portability

Linux is an extremely portable operating system which supports all different flavours of hardware. Programming inside the kernel implies programming in a portable menner. One major issue concerning the portability of C Code is the size of spe- cific data types. A word is known as the entity which a machine can process in one cycle—this is the size of a general purpose register within a CPU. The size of a word equals the size of a pointer. But the size of a word counted in bits differs from one architecture to another. On widely used Intel IA32 CPUs one word is four bytes long which corresponds to 32 bit. But on a new Intel IA64 CPU a pointer is 64 bits wide. It gets even trickier because if we work on a 64 bit machine we cannot make any as- sumption about the size of an integer in bits. Appendix A gives an overview of the different data type sizes of different architectures. For this reason the kernel developers introduced Opaque Data Types which do not offer their internal format or their actual size. pid_t or atomic_t are examples for such data types—the developer should never make any assumptions about the actual size of them. Furthermore there are Special Types and Explicitly Sized Types. Special Types must be stored in an explicit manner, e.g. the types jiffy or flags are always stored as unsigned long. The Explicitly Sized Types are of much greater interest in this implementation project, especially regarding the networking part of the L2CAP module. Explicitly Sized Types help the developer to ensure meeting the requirements of the specification. If a networking packet follows a specific composition we want to ensure access of portions of this packet in the right manner. This means we need to know how to access a byte or a 16 bit field. Therefore each architecture within the kernel defines corresponding data types for generic data types with an explicit size. That means that no matter which architecture we are currently running the kernel on,

12 get_unaligned() example: For layer. L2CAP the in structures packet and frame of kinds different called attribute net- specific with compiler work a we all if by undesirable together packed very sizes. are different is aligned—they of naturally This fields not different usually developer. are the that packets by though work even visible types not internal called is sized technique differently this a with uses structures compiler the enlarges Therefore which type. padding biggest its of alignment used the ways commonly the like tures GCC like compilers architectures automatically. a Modern Some problems architectures For CPU-trap. alignment RISC zero). expensive those most an are avoid which size. causes in bits location data its especially significant memory mis-aligned of least a alignments; of two load at these multiple stored the concerning a is that strict is it (so quite which if 4 are location aligned of naturally multiple a is a at type is stored bit is 32 a it example if aligned naturally is Alignment Endianess and Alignment 2.2.1. to by applies represented same always is byte unsigned an eligmcie eei enlmco eptedvlprt ovr h network the forth. convert and to back developer host un- the the the to help of data macros anything to kernel an assuming has Generic without on developer correctly machine. the used processed Therefore derlying be always user. the is should by data that chosen that be endianess ensure can endianess—the example, its for machine in IA64 fixed is connection. architecture the called over ery read are and methods sent be two to The going is data position. way last which byte pro- the significant The least at the or word. storing and in position one either first within word stored the one (see within are at bytes long bytes the bytes which order eight can in cessor or order four the two, describes ordering one, is it if matter no [ item, also data every for work nlge aawti yesra hudb cesdb sn h w macros two the using by accessed be should stream byte a within data Unaligned is Responsible padding. any without structures those pack to us permits GCC But struc- data complex uses one whenever problem a becomes dependancy this But h ovrint rfo h ott h ewr samjrcnen o ev- Not concern. major a is network the to host the from or to conversion The the is issue major Another iteEndian Little obte al. et Corbet _trbt_ (pce )); packed (( __attribute__ } tutlcpcdhr{ l2cap_cmd_hdr struct ecie h oiinn fadt emn ihnmmr.Avariable A memory. within segment data a of positioning the describes _8iet; ident ; code __u8 __u8 _e6len; __le16 u32 okn ihntokn akt nocstepeiedfiiinin definition precise the enforces packets networking with Working . and , 2005 and put_unaligned() ae294]). page , u64 respectively. , byte-order struct _trbt_ ((packed)) __attribute__ endin defined nCbcueteaineto tuti al- is struct a of alignment the because C in fteudryn rhtcue h byte- The architecture. underlying the of u8 nusge 6btitgrby integer bit 16 unsigned an , hsi sdwti all within used is This . hs macros Those . ..Portability 2.2. i Endian Big u16 the ; 13

2 2. Linux Kernel Development

The Bluetooth specification defines its data to be in little endian format. That means we mainly use macros like __le16_to_cpu() or __cpu_to_le16(). The same can be done with data of size 32 bit or 64 bit.1 If the underlying architecture uses the same endi- aness as the network packet, say an Intel IA32 machine with little endian order, the macro is empty and no conversion takes place.

2.2.2. Concurrency and Race Conditions

Concurrency describes the situation in which the system tries to do more than one thing at once. This is not a problem on a simple single processor system, but multi- processor systems and a preemptible kernel means that we can lose the processor at any given time. Further reasons for concurrency besides multiprocessor systems and kernel preemption are asynchronous Interrupts, Softirqs and Tasklets. [see also Love, 2005, page 176] “Concurrency-related bugs are some of the easiest to create and some of the hardest to find.” [Corbet et al., 2005, page 106] Concurrency can cause Race Conditions, Deadlocks and Starvation of different pro- cesses.2 That means access to shared data has to be controlled by the programmer, otherwise the results are unpredictable. Operations on data structures must be exe- cuted atomically. Larger sections of code need to be protected within a critical section; that is code that can be executed by only one thread of execution. The Linux kernel offers a wide variaty of different primitives for different needs. One of the first facilities included was the so-called big kernel lock. This turned the entire kernel into one big critical section which allowed the developers to work on SMP systems. But this solution did not scale very well and shortly new techniques were introduced to offer the developer a finer-grained locking scheme. Today’s Linux kernels come with a variety of mechanisms that allow protection of critical sections and atomic operations. The kernel offers Reader/Writer Semaphores (including Mutexes), atomic variables (type atomic_t), atomic bit operations (set_bit, clear_bit, change_bit, . . .) Seqlocks and Reader/Writer Spinlocks for code that cannot sleep, like interrupt handlers. Even if all specific needs seemed to be addressed by these techniques, “fine-grained locking comes at a cost, however. In a kernel with thou- sands of locks, it can be very hard to know which locks you need—and in which order you should acquire them—to perform a specific operation.” [Corbet et al., 2005, page 123] Some data structures like sockets and socket buffers provide their own locking scheme. The most critical data structure in our code is the socket specific struct l2cap_pinfo which maintaines the device’s L2CAP channel and socket info.

1Note that an 8 bit field (one byte) does not need any conversion. 2For an indepth discussion about these topics refer to [Tanenbaum, 2001, chapters 2 and 3]

14 Kunst 2005 oeaottekre otblt n ycrnzto suscnb on n[ in found be can issues synchronization and portability kernel the about More hpe ,9ad1] [ 19], and 9 8, Chapter , , 2006 hpe . n 9.3]. and 6.5 Chapter , obte al. et Corbet , 2005 hpe n 1 n [ and 11] and 5 Chapter , ..Portability 2.2. ud and Quade Love 15 ,

2 3. Conguration Process

Before we actually use flow control between two entities, the two devices need to ne- gotiate appropriate settings for their channel utilization. This is all done during the configuration process which starts immediately after the connection establishment when we start into a so-called BT_CONNECT state. Each device needs to configure specific parameters for its incoming and outgoing logical link before attempting to use the channel for data transmission. Using information requests is an optional way to retrieve specific information about the peer’s further abilities albeit it is mandatory to use information requests prior to using extended features such as the retransmis- sion and flow control mechanism in a configuration request. Any incoming informa- tion request shall be answered by an appropriate information response.

3.1. Information Retrieval

The information retrieval consists of two possible signalling packets, namely infor- mation requests and information responses. They are used prior to the actual config- uration requests to ask for implementation specific features from the remote entity. If we want to use flow control within the L2CAP layer it is mandatory to use in- formation requests before we put the retransmission and flow control option into a configuration request packet.

3.1.1. Information Request

The information request checks the peer’s ability for optional features such as flow control mode. The data packet itself consists of the unique code (0x0A) followed by a unique channel identifier, the fixed length (2 octets) and the information payload in the form of an InfoType field which consists of either 0x0001 for the request of a connectionless MTU or 0x0002 for the request of extended features. We are mainly interested in the latter one. All other values are currently reserved for future use.

3.1.2. Information Response

The information response must be sent upon receiving a valid information request. The response data packet consists of the code (0x0B), the unique identifier which

16 niao o h eghaddt oto fterpnepce.Ti en ihra code. either result response’s means be the This will in else unsupported packet. requested—everything as are reponse treated features the extended of or an portion size as data MTU serves connectionless and request length corresponding the the for of indicator field InfoType The immediately. response peer. we remote if the request to to configuration request response a information connection of an reception send a already the of not after reception did or the process configuration after the either start issued is request information () field of Data 4 the [Vol. in in described 56]: Bit being in page corresponding as 4.12, accessible the Packet being setting Response as Information by feature the done this of is promote This to have implementation. we our usable Control Flow make To Mask Features Extended which 3.1.3. octets 4 contains it request retrans- to the are of mask. case we features In extended that the InfoType. feature of the consist control on dependant flow are and field mission data the ( of success contents either The and indicate basically code, can result result a InfoType, the field, length variable data. optional a the one, request’s the matches new eev nifrainrqetw rpr naporaeinformation appropriate an prepare we request information an receive we Once by code our in served are requests information Incoming i.e. information, requested the of value the matches field InfoType The n noigifrainrsossaesre by served are responses information incoming and pcfidwihsalb e o1i h etr sspotdadstt 0 to set and is set supported bit be is shall single feature bits a feature the feature unassigned 0”. if to or each 1 reserved, For unknown, to All set 55). otherwise. be page shall on which 4.11 specified Section (see field data Tefaue r ersne sabtms nteIfrainResponse Information the in mask bit a as represented are features “The 31 1 No. idrcinlQS02 0 0 0 QoS Bi-directional 2 Mode Control Flow 0 eevdfrfauems extension mask feature for Reserved Mode Retransmission feature Supported al 3.1.: Table xeddFaue Mask Features Extended 0x0000 rn vial upr ( support available no or ) l2cap_information_rsp() 3 0 Octet ..IfrainRetrieval Information 3.1. l2cap_information_req 7 1 Bit BlueSpec 0x0002 section , 0x0001 The . An . 17 ).

3 3. Configuration Process

3.2. Conguration Request

A configuration request is an essential signalling packet for the purpose of negotia- tion: “Configuration Request packets are sent to establish an initial logical link transmission contract between two L2CAP entities and also to re- negotiate this contract whenever appropriate”. [BlueSpec, page 47] Each configuration request is exclusively related to either the incoming or the outgo- ing traffic. In case of the retransmission and flow control option, such a configuration request determines the incoming values of a sender’s request. For example, consider device A sending a request to device B wishing to configure retransmission and flow control with a TxWindow size of 32. This value serves as the window size for incom- ing traffic related from device B to device A even if the remote peer (here device B) certainly has to keep track of negotiated values and is therefore also involved. Even if all default values are acceptable from the beginning a configuration request needs to be sent in order to proceed with data transmission. In such a case it is per- fectly valid to send an empty request and no explicit options. Device’s configuration requests refer always on their own: “The configuration request cannot request a change in the parameters the device receiving the request will accept”. [BlueSpec, page 47] The architecture of a configuration request packet is shown in figure 3.1. It consists of six fields, namely the unique code (0x04), the identifier, the whole packet’s length (the variable size depends on the following options), the destination’s CID, a 16 bit flags field1, and finally the configuration options.

LSB MSB

Code = 0x04 Identier Length

Destination CID Flags

Conguration Options

octet 0 octet 1 octet 2 octet 3

Figure 3.1.: Configuration Request Packet

The specification currently defines four possible configuration options, namely the Maximum Transmission Unit (MTU), the Flush Timeout, Quality of Service (QoS) and

1Currently there is only one flag defined which serves as a continuation flag if the receiver’s MTU is not large enough to receive a whole specific configuration request at once and fragmentation of the request’s packet needs to take place.

18 htoption say option, that unknown an for parameters configure 0x42 to wishing request configuration a options different code. 127 option’s the handle to us allows this because 128 size of (code array an use to (code option respectively. control flow and retransmission the whereas union a is which config- one sent latter at all stored The is of codes code. codes result result result separated individual overall the the the all store as of to well bytes as 128 options size uration of array an up hsvlewscoe si a ee eue nara eus n ol have would 0 and request real a undesirable. in is which used default be by never option single can every it for success as stated chosen was value This in stated as defined codes result possible four currently table are There option. incoming a as used being only bit be significant to most field code option’s the defines specification has to option MTU corresponds the which example array For the specification. the within by place given code is unique that its code option’s at the stored is result option’s yemlil ie,freapeMU+RC+MU nsc aew decided defined we we case that a realize To such option. In test_bit each MTU. of ( + occurrence bitmask first RFC a very + the MTU only example consider to for times, multiple type discussed is section option in RFC depth The in implementation. this in macroname corresponding their Control Flow and Retransmission esol epeae o uhabgnme fotosbcuei aew receive we case in because options of number big a such for prepared be should We code with option no is there that herein is effect side helpful The (in request configuration incoming an receive we Once l ed ihntersl ra r ntaie ih255: with initialized are array result the within fields All ehv orsodwt ofiuainrsos nomn h eoepeer remote the informing response configuration a with respond to have we , 0x01 3.3 est(eut,25,LCPMXOT ); L2CAP_MAX_OPTS , 255 , (result memset 0x00 0x04 0x02 x3Qaiyo evc QS Option (QoS) Service of Quality 0x03 (MTU) Unit Transmission Maximum 0x01 Code . . al 3.2.: Table n ssoe at stored is and antb sd.Ti iesol esfcetfralftr eessa the as releases future all for sufficient be should size This used). be cannot nindln options long unsigned 0x42 ernmsinadFo oto Option Control Flow and Retransmission Option Timeout Flush Type sukon hti h ehv oke rc fec possible each of track keep to have we why is That unknown. is 3.4 osbetp ed o h ofiuainoto format option configuration the for fields type Possible oeta h pin edmycnana pino specific a of option an contain may field options the that Note . result[1] l pin r ldi table in filed are options All . hti sdvateaoi macros atomic the via used is that ) hint ( result[L2CAP_CONF_MTU] nysvnoto ih iscnb sdfor used be can bits eight of out seven only , result[0] n octet one ahpsil configuration possible Each . L2CAP_CONF_RFC L2CAP_CONF_QOS L2CAP_CONF_FLUSH_TO L2CAP_CONF_MTU Macroname ..Cngrto Request Configuration 3.2. l2cap_config_req() 0x04 nteimplementation) the in og ie h octet’s the Given long. ssoe at stored is ) 3.2 o eeec with reference for 0x00 edecided We . set_bit result[4] eset we ) and 19

3 3. Configuration Process

Result Description 0x0000 Success 0x0001 Failure  unacceptable parameters 0x0002 Failure  rejected (no reason provided) 0x0003 Failure  unknown option Other Reserved

Table 3.3.: Possible configuration response result codes

The result array is passed forward to l2cap_parse_conf_req(). This function parses a given configuration request for all different options. It sets the appropriate con- figuration request parameters from the remote peer if all options are valid and un- derstood. It rejects them if they are malformed and prepares an unknown status for options that we do not support yet. The individual result code for each seperate option is set via l2cap_check_conf_opt() which checks this specific option for valid parameters.

3.3. Conguration Response

Another part of the configuration process comes into play once we received a valid request and need to build a matching response. This situation occurrs when we ran through the aforementioned configuration request parsing process. Within the function l2cap_config_req() we call l2cap_build_conf_rsp() to build such a response packet. The function takes a pointer to the result array which was just set up. It runs through the following steps:

(1) Check the value of the overall result code result[0] to take appropriate action. Be aware that this is the indicator for the result code of the entire packet:

“The result of the configuration transaction is the union of all the result values. All the result values must succeed for the configuration transaction to succeed”. [BlueSpec, page 49]

We distinguish five different cases—the four specified result codes (see table 3.3) plus an empty request that needs to be answered as well.

(2) Within each case of the overall result code we check every single entry of the array for the same result code. For example consider a configuration request that is treated as successful for all single configuration options and made us set result[0] = L2CAP_CONF_SUCCESS;

20 upr o euse pin ti motn ont htti pini ob in- be to is options provided. sent option be a the this to is of reasons option that which possible any know last note side The to requesting understood. the important the be let cannot is in to It response sent the if within option. accepted cluded requested been a have for would support that [ values request.” pa- “the an different original of all the case contains set In finally response values. us the requested lets which the peer match remote to the rameters of by case accepted In fully codes. is result request different the of understanding ough figure in octet shown one is a packet is response there configuration more a further of and CID source request— a uses configuration field it a CID as destination fields a same of the instead basically of consist packets proper response a tion build to request. and valid options a different as all well the for as available that generically packet next so response used length the and be to type can point option’s to itself the function option for function the demands pushed of signature the end function’s of the The length At option. in stored. increased finally is are options pointer all this where location the to pointer aaee pin.Tebscfra silsrtdi figure in illustrated is format configuration offers basic L2CAP The parameters configuration options. extending parameter of Option purpose the Control For Flow and Retransmission 3.4. (3) eedn ntegvnrsl oeaporaeato stkn hsipisathor- a implies This taken. is action appropriate code result given the on Depending by handled is response configuration incoming An digsc noto sdn via done is option an such Adding result pint h ofiuainrsos htw build. we that response (e.g. code configuration entry the the the to option for check match array cases the both within If entries remaining 127 all L2CAP_CONF_SUCCESS check us makes This S MSB LSB hc ae n ftersl oe ftable of codes result the of one takes which oe=00 Identier 0x05 = Code ce ce ce ce 3 octet 2 octet 1 octet 0 octet BlueSpec iue3.2.: Figure oreCID Source Result . ae5]An 51] page , ofiuainRsos Packet Response Configuration l2cap_add_conf_opt() ..Rtasiso n lwCnrlOption Control Flow and Retransmission 3.4. nnw Option Unknown 0x01 Reject for l2cap_config_rsp() 3.3 3.2 ncetbeParameters Unacceptable Length Cong L2CAP_CONF_MTU Flags . npage on alr hc osntneed not does which failure hsfnto eevsa receives function This . Success alr niae missing indicates failure 3.3 The . 20 h architecture The . h configuration the n d this add and ) Type Configura- . specifies failure 21

3 3. Configuration Process the option type field of the parameters that are to be configured. The four currently

specified options are shown in table 3.2.

ÄËB ÅËB

ÌÝÔ e ÇÔØiÓÒ DaØa

ÄeÒgØh

Figure 3.3.: Configuration option format

Note that the option data field can consist of multiple options within one single request. The Retransmission and Flow Control option format itself is specified as drawn in figure 3.4. The whole option is 11 bytes long and the different fields are discussed in this section. 0 31

0x04 Length = 9 Mode TxWindow size

Max Transmit Retransmission time-out Monitor time-out (least signicant byte) Monitor time-out Maximum PDU size (MPS) (most signicant byte)

Figure 3.4.: Retransmission and Flow Control option format

Mode (1 octet) This field is the final instance about the link mode that is to be used for this connection. The different values for this field are specified in table 3.4. The default is the Basic L2CAP Mode and using this mode invalidates all other fields within this option.2 TxWindow (1 octet) The TxWindow size field has to be set accordingly to the avail- able buffer space for flow control. The size reflects the available buffer space counted in frames and may vary between one and 32. For a better channel uti- lization a larger value is recommended. The sending delay is influenced by this value, too. The transmitter can send as many PDUs as fit within the receiver’s TxWindow. Max Transmit (1 octet) This field’s value specifies the number of possible retrans- missions of a single I-frame in Retransmission Mode—therefore it is of no interest for Flow Control Mode. 2It is not entirely clear why the Extended Features are propagated when it basically comes down to the use of the Basic L2CAP Mode for each connection as seen on the Siemens S75 mobile phone which claims to support all extended features but never allows us to make use of them by signalling a value of 0x00 for the Mode field in the Retransmission and Flow Control Option.

22 aiu D ie( octet) (1 Size PDU Maximum octets) (2 Time-Out Monitor octets) (2 Time-Out Retransmission 3 oeta h ups ftertasiso ie nFo oto oei culyntfrthe for not actually is Mode Control Flow in timer retransmission the of purpose the that Note cnwegmns tealstesnigpe ocniu transmission. continue to peer sending the enables It acknowledgements. retransmission httedvc scpbeo accepting. of capable is device the that lost. of got supervision I-frames or the transmitting acknowledgements is on if keep value timer to time-out this side the after of transmitting Retransmission I-frames the purpose the leads the This of mode transmissions. initilization Control I-frame the Flow for In used Timer. primarily is and milliseconds etfaei ob etaanadtetmrsalb etre.Tetmrshall periodic have timer to The directions. connection both restarted. idle in be an sent enforces shall traffic and timer monitor state the open and the again in acknowledge- active sent last remain be the to Monitor-Timer is the of active frame be expiration ment shall Upon timers time. two acknowledgements the given lost of any one at that only that ensures Note which retransmitted. are timer (S-frames) monitor the of initialization al 3.4.: Table fls -rmsbtmr opeettetasiso rcs osokdet lost a to due stock to process transmission the prevent to more but I-frames lost of osbemd entoswti h F option RFC the within definitions mode Possible x2Fo oto Mode Control Flow Mode L2CAP Basic 0x02 0x01 0x00 Value te values Other hsi h au nmlieod hti sdfrthe for used is that milliseconds in value the is This hsi h ieo h aiu D ala size payload PDU maximum the of size the is This ..Rtasiso n lwCnrlOption Control Flow and Retransmission 3.4. ernmsinMode Retransmission Description eevdfrftr use future for Reserved hsvlerpeet h ieotgvnin given time-out the represents value This 3 23

3 4. Procedures for Flow Control

After the mandatory configuration process as the first part of the procedures for flow control in L2CAP we are now actually entering the stage of transmitting and receiving data in flow control mode. Two frame formats are specified for this mode: The I- frame (Information frame, to transport information payload instead of the B-frame in Basic L2CAP Mode) and the S-frame (Supervisory frame, to control the transmission of

I-frames). Both frames are illustrated in figure 4.1.

ChaÒÒeÐ

ÄeÒgØh

FCË

CÓÒØÖÓÐ

ÁD

ÄËB ÅËB

½6 ½6 ½6 ½6

ËÙÔ eÖÚi×ÓÖÝ FÖaÑe ´Ë¹FÖaÑeµ

ËDÍ

ChaÒÒeÐ

ÄeÒgØh ÁÒfÓÖÑaØiÓÒ ÈaÝÐÓad

FCË

CÓÒØÖÓÐ

ÄeÒgØh

ÁD

ÄËB ÅËB

½6 ½6 ½6 ¼ ÓÖ ½6 ½6

ÁÒfÓÖÑaØiÓÒ FÖaÑe ´Á¹FÖaÑeµ

Figure 4.1.: L2CAP PDU formats in Flow Control Mode

The L2CAP Header The fields length and CID build the L2CAP header. The Length field consists of two octets and contains the size of the entire L2CAP PDU in octets, excluding the header itself. The specification states that the maximum length varies between 65,529 octets and 65,531 octets depending on the presence of the L2CAP SDU length field. This field is present when the SDU spans more than one I-frame and yields the size of the total SDU which consists of multiple information payload fields of different I-frames. Whether this 2 octets are to be considered as the SDU length field or not is specified within some bits of the Control field. The Control Field The control field is 2 octets long and is used in both S-frames and I-frames. Its archi- tecture is illustrated in figure 4.2. The right-most bit of the control field distinguishes the frame’s type by being either set to 0 (I-frame) or 1 (S-frame). Only I-frames can be used to transfer information whereas both frames can be actually used to signal

24 hl o eused. code be (Reject, frame not REJ shall the is one other the and of field control the within occur states: only possible do four bits of one These represent segmented. and I-frames is SDU L2CAP an if this of scope the beyond are and But Mode Control Reject-frames. Flow so-called work. to the of apply request use not do the may techniques allow S-frames both and Mode I-frames missing Retransmission of the retransmission Within acknowledgement. an udnycekoe h hl rm,icuigteLCPhae.Tegenerator The header. L2CAP the including frame, is polynomial whole the over check dundancy The Sequence Check Frame The encoding (The defined types possible four of two only 10 are there Currently Mode. S-frame. Control Flow in place take got that not frame does specific retransmission a But of retransmission lost. request to receiver the sequence allow receive would the Mode number Retransmission In frames. received previously side knowledge transmitter his the that on started indicates is receiver timer the signalling. monitor monitor one, The timer to retransmission to the I-frames. disable transmitting set shall sender stop bit the and that this and full with is buffer frame receive internal a receives sender the The 11 10 01 00 The ial hr stetobt long bits two the is there Finally numbers sequence two The and ernmsinDsbeBit Disable Retransmission rm hc Sequence Check Frame speeti l otnainfae fa 2A SDU. L2CAP an of frames continuation all in present is SDU. L2CAP segmented a of frame end accordingly the set signals respectively. be condition receiver to the this needs by and recognized When present and SDU. transmitter is the L2CAP field by length segmented SDU a L2CAP the of applies frame start the represents SDU. L2CAP unsegmented an specifies emnainadReassembly and Segmentation 01 r eevdfrftr s) n steR rm Rcie ed,code Ready, (Receiver frame RR the is One use). future for reserved are F g Ì ÖaÑe × ( ÝÔ e Ë Á D = ) ½6 × × ËAÊ D ½5 16 iue4.2.: Figure FS tteedo ahS n -rm om ylcre- cyclic a forms I-frame and S- each of end the at (FCS) + ½4 D R spr fayFo oto mlmnain When implementation. Control Flow any of part is (R) ½¿ ReqSeq 15 ÊeÕËeÕ ÊeÕËeÕ + ½¾ uevsr function Supervisory is(A)aeue odsigihdfeetframes different distinguish to used are (SAR) bits D ½½ oto il Formats Field Control 2 and + ½¼ ,[see 1, TxSeq 9 Ê Ê 8 01 BlueSpec .I lwCnrlMd E frames REJ Mode Control Flow In ). r sdt ubrfae n ac- and frames number to used are × × × 7 6 S hc ak h yeo the of type the marks which (S) Ì 5 ae3] h iu kernel Linux The 39]. page , ÜËeÕ 4 Ë ¿ ¾ ¼ ½ ½ ¼ 00 25 )

4 4. Procedures for Flow Control offers a crc16() function within which covers exactly the aforemen- tioned generator polynomial. It can be used to create a frame check sequence, for example: /* calculate fcs over information payload plus * len, cid and control fields */ fcs = crc16(0, skb->data, len + 6); or to detect invalid frames (in l2cap_invalid_frame_detection()): /* contains an fcs error */ fcs = get_unaligned((u16 *) (skb->tail - 2)); if (unlikely(fcs != crc16(0, skb->data, skb->len - 2))) err = -3; Figure 4.3 illustrates the segmentation process between different layers. The SDU is composed of multiple information payload fields of different I-frames. Note that the entire protocol overhead, like the L2CAP header, the control field, or the frame check sequence are stripped for the SDU composition. The SDU length field is only present in the first I-frame of a series of I-frames that belong to a segmented SDU and is marked in bright gray within this figure. For illustrating purpose, parts of the HCI layer and its interaction with the L2CAP layer are shown as well. We see how multiple HCI data payloads compose an I-frame.

This is done transparently to the L2CAP header on which this work is based.

ÄeÒgØh ÁÒfÓÖÑaØiÓÒ ÈaÝÐÓad

CÁD ËDÍ ÄeÒ FCË

CÓÒØÖÓÐ

ÄeÒgØh ÁÒfÓÖÑaØiÓÒ ÈaÝÐÓad

CÁD FCË CÓÒØÖÓÐ

ľCAÈ

ÄeÒgØh ÁÒfÓÖÑaØiÓÒ ÈaÝÐÓad

CÁD FCË

CÓÒØÖÓÐ

ÀCÁ daØa ÔaÝÐÓad

ÀCÁ daØa ÔaÝÐÓad

ÀCÁ

ÀCÁ daØa ÔaÝÐÓad

Figure 4.3.: Example of the segmentation process between the L2CAP and HCI layers

26 eakolde yterciigpe.Ti cnweg tt aibesalbe I-frame single of shall value a variable the of yields state acknowledgement side An acknowledge remote the too. This from endpoint, remote peer. each receiving for maintained the by acknowledged be ( transmit exceed to decides sender the NextTxSeq I-frame Once in-sequence endpoint. new remote each a for transmitted the maintained of be field shall control the within provided I-frame. be will and sequentially I-frame namely variables, internal ExpectedTxSeq different three uses peer sending The peer sending The 4.1.1. 63. to 0 of figures peer’s range by the remote illustrated in are the peer. are variables and receiving variables specific the buffer with and own used peer its techniques sending of The the status between current distinguish We the respectively. sequence of buffer and track variables keep internal some to of numbers use the requires Control Flow Numbers Implementing Sequence and Variables 4.1. TxWindow 1 ernmsinMd losrtasiso faraysn -rmsfrwihtevleof value the which for I-frames sent already of retransmission allows Mode Retransmission oetefloigrqieetgvnb [ by given requirement following the Note Finally utntb changed. be not must ReqSeq ReqSeq ExpectedAckSeq I valid a “If NextTxSeq ExpectedAckSeq siceetdb n.B wr ht“h au of value “the that aware Be one. by incremented is ”[ )” valid A . ≤ BlueSpec h edsqec number sequence send The . NextTxSeq ReqSeq ttstenme ftenx e -rm ob rnmte and transmitted be to I-frame new next the of number the states iue4.4.: Figure ReqSeq ae89]. page , ymr hntemxmmnme fottnigI-frames outstanding of number maximum the than more by ”. srcie rmtepe then peer the from received is eet h urn au ftenx -rm xetdto expected I-frame next the of value current the reflects 1 h au of value the au soeta si h range the in is that one is value xml fteTasitrsside Transmitter’s the of Example ExpectedAckSeq TxSeq TxSeq BlueSpec ..VralsadSqec Numbers Sequence and Variables 4.1. sstt h n of one the to set is sue onme ahtransmitted each number to used is ae90]: page , ExpectedAckSeq sits as 1 + NextTxSeq ExpectedAckSeq TxSeq ReqSeq , 4.4 NextTxSeq NextTxSeq ... hl not shall .] . [. sstto set is value. and ≤ 4.5 TxSeq All . and and 27

4 4. Procedures for Flow Control

Figure 4.4 illustrates the use of all variables for the transmitter. The negotiated TxWindow size is five and all the frames F2 to F6 have already been transmitted but not yet acknowledged. The first acknowledgement is expected to match frame F2. But note that once we receive an acknowledgement for any frame that still needs to be acknowledged (here frames F2 to F6) all frames up to (but not including) this frame are acknowledged even if either one of the frames in front of it or one of the acknowledgements got lost. For example suppose the value of ExpectedAckSeq to be 2 as seen in the figure men- tioned above. If the sending peer receives a valid frame from the receiving peer (of which the ReqSeq value is implicitly counted as an acknowledgement number) which sends an acknowledgement with ReqSeq = 5, we assume the frames 2, 3 and 4 to be implicitly acknowledged. Only within Retransmission Mode action can be taken on the frames 2, 3 and 4, which is beyond the scope of this work.

4.1.2. The receiving peer

Three internal variables are defined for the receiving peer, namely the receive se- quence number ReqSeq, the receive state variable ExpectedTxSeq and the buffer state variable BuerSeq. Figure 4.5 shows an example of how all of these variables come

into play on the receiver’s side.

Figure 4.5.: Example of the Receiver’s side

ReqSeq is used in I-frames as well as in S-frames to acknowledge correctly received frames with corresponding TxSeq values up to and including ReqSeq − 1. Therefore the value of ReqSeq shall be set to the current value of ExpectedAckSeq or BuerSeq (which of these values are to be used is implementation specific and discussed in the next paragraphs). ExpectedTxSeq reflects the expected TxSeq value of the next in-sequence I-frame. The buffer state variable BuerSeq provides the delay of acknowledging frames un- til they have been pulled by the upper layers. This mechanism prevents the receiver of buffer overflow. The values of ExpectedTxSeq and BuerSeq are equal when no segmentation takes place and frames are pushed to the upper layer immediately on

28 on ntersosblt iswti h 2A layer. L2CAP the within lies responsibility the on point by programming called network is UNIX which in tion done is matter based a socket a in data Retrieving Data Retrieving 4.2. h pinldbgotu u a eipeetdltrt neatwt h srin- user the with interact to later convenience. implemented for be within only terface may used but ap- currently output conditions is debug reporting error exceeds optional Error these that silently. the dropped of length is one a PDU or Whenever whole CID the (MPS). plies unknown size check an PDU payload frame like PDU the wrong frame maximum a case the the like in which errors fields cover in wrong conditions or mentioned Those sequence are invalid. as reasons regarded possible be shall seven where 3.3.6] section Detection Frame Invalid 4.2.1. the via layer of upper size the the to buffer checking al- socket an was except the received case—which passing taken sock_queue_rcv_skb() we latter and be validity if the to for In or payload is Mode information Mode. action Control L2CAP Flow more Basic whether in implemented—no in result S-frame ready are the or we upon I- if decide an B-frame and handle ordinary operate to we about which is are in CID we stage the the if check channel we connectionless Herein a into move can 0x0002 we CID Elsewhise header’s frame the given process. if the uration channel signalling on a based into received, step either be is we can means that This CID. frames header’s of kinds three between place L2CAP the of part beneath layer not HCI for is the handler when itself signal play function the into invokes comes this layer that L2CAP The Note implementation. layer fulfilled. are checks various of range the in be shall I-frames of TxSeq numbers Sequence reception. eto nFo oto oe h rto ait fsescnit favalidity a of consists steps of variety a of re- first frame The handle to in necessary Mode. check are Control Mode Flow L2CAP Basic in in ception those than steps more Quite recvmsg h oto o oe nto on moves flow control The h pcfiainsae [ states specification The 0x0001 TxSeq edTxSeq < nalohrcssw s aacanland channel data a use we cases other all In . O eep fa -rm with I-frame an of receipt “On hc oesalsrso inligpcesta eswdrn h config- the during saw we that packets signalling of sorts all covers which , ( l2cap_invalid_frame_detection() BuerSeq al uhacl smthdi h 2A ae yasga ade func- handler signal a by layer L2CAP the in matched is call a Such call. rae than greater hl eiceetdb eadeso o ayIfae with I-frames many how of regardless 1 by incremented be shall + bt_sock_recvmsg . TxWindow ExpectedTxSeq BlueSpec l2cap_recv_acldata() l2cap_recv_frame() ) . ae92]: page , hri h eesr oktbfe sfildand filled is buffer socket necessary the wherein eepeiul received”. previously were TxSeq hsfnto orsod o[ to corresponds function This . qa to equal hr titdfeetaintakes differentiation strict a where namely , l2cap_data_channel() ExpectedTxSeq recv_acldata ..Rtivn Data Retrieving 4.2. ExpectedTxSeq , Expect- rmthis From . BlueSpec scalled. is 29 ≤ ,

4 4. Procedures for Flow Control

One extra check was implemented within this function. It is the very first check that is performed and covers the assumption that each single socket buffer matches exactly one frame. This condition is validated by the following code snippet: len = get_unaligned((u16 *) skb->data);

if (len != (skb->len - L2CAP_HDR_SIZE)) err = -1; This assumption is correct because a complete frame is copied into a newly created socket buffer (conn->rx_skb) in l2cap_recv_acldata and the size of the newly allocated memory area of conn->rx_skb is set to the same size that is specified in the frame’s header.

4.2.2. Process the Send Sequence Number TxSeq

The send sequence number TxSeq, that can only be present in I-frames, is set by the transmitter to its internal sequence number NextTxSeq. The receiver yields an internal variable called ExpectedTxSeq that reflects the value of TxSeq expected in the next I- frame. Another internal variable on the receiver’s side, BuerSeq, is used to delay acknowledgement of received I-frames when segmented I-frames are buffered. Basically four error checks are done within l2cap_process_reqseq(). First of all the sent TxSeq value is compared to the expected one. In case of success the ExpectedTxSeq is incremented by one and everything is fine: if (txseq == pi->exp_txseq) { pi->exp_txseq = (pi->exp_txseq + 1) % 64; } If this condition does not apply we check for an out-of-sequence I-frame and re-adjust the ExpectedTxSeq value: else if (((txseq - pi->buffer_seq + 64) % 64) < pi->itxw) { /* out-of-sequence i-frame */ pi->exp_txseq = (txseq + 1) % 64; } The last two checks cover the case of a duplicated I-frame or an invalid TxSeq se- quence number in which an error is returned and the whole frame is dropped.

4.2.3. Process the Receive Sequence Number ReqSeq

The ReqSeq value within the control field must be processed in I-frames as well as in S-frames. A basic error check is fulfilled at the beginning of l2cap_process_reqseq() by checking the status of the right-most bits. In case of an I-frame the very last bit shall be coded 0, and in case of an S-frame the four right-most bits shall be coded 0001 because the two S bits of the supervisory function are always encoded 00 (marking the

30 orsodn oto ed h rtato ob ae ntesce ufri to field is control buffer the socket header, the L2CAP on the sequence: taken namely check frame be it, the the from of to and value fields action extracted unnecessary first the the and The remove buffer socket field. a of control form corresponding in in I-frame done an actually receives is function PDUs multiple of SDU the Reassembling SDU the Reassemble 4.2.4. current the to set within type account: S-frame into valid only the is this and Ready) Mode. Control Receiver Flow type of be to S-frame 2 hserrcniinwudhv ob hne lgtyweee ernmsinMd sgigto going is Mode Retransmission whenever slightly changed be to have would condition error This hsts sacmlse ytefloigcode: following the by accomplished is task This fthe If [ takes implemented mechanism checking error next The eipeetdadRJfae a occur. may REJ-frames and implemented be } f(( esq-p >epake 4 4<= 64 % 64) + exp_ackseq */ -> pi - error reqseq sequence (!(( if reqseq /* *rmv edr,cnrladfsfo -fae*/ frame i- from fcs and control , header remove /* euneerror”. Sequence invalid an contains which Seq received is I-frame or ReqSeq S-frame valid a when ter k_rm(k k >ln-LCPFSSZ ); ); L2CAP_FCS_SIZE L2CAP_CONTROL_SIZE - + len -> skb , (skb L2CAP_HDR_SIZE skb_trim , (skb skb_pull h 2A niysalcoetecanla osqec fan of consequence a as channel the close shall entity L2CAP The “An ReqSeq ≤ ReqSeq ReqSeq au.A invalid An value. p >nx_xe i- x_csq+6)%6) { 64)) % 64) + exp_ackseq -> pi - next_txseq -> (pi k- ker=EONEE ; ECONNRESET = ; BT_DISCONN = sk_err -> sk sk_state -> sk *coecanl- eddsonc eus */ request disconnect send -> channel close /* e.si _p_ol1 2a_i(k >cd); ->scid (sk) ); l2cap_pi ->dcid ( (sk) l2cap_pi ( __cpu_to_le16 = __cpu_to_le16 scid = req. dcid req. eun-2; return ; ->conn (sk) l2cap_pi = conn * ; req l2cap_conn l2cap_disconn_req struct struct 2a_edcd(on,lcpgtiet(cn ), conn ( l2cap_get_ident , (conn l2cap_send_cmd 2a_oksttmr(k,H 5); * HZ , (sk l2cap_sock_set_timer au svldadi-eune h internal the in-sequence, and valid is value ReqSeq ≤ 2 euneerrecpincniinocr ntetransmit- the in occurs condition exception error sequence NextTxSeq value. 2A_ICN_E ief(e) &req); (req), sizeof , L2CAP_DISCONN_REQ ReqSeq . soeta snti h range the in not is that one is BlueSpec l2cap_reassembly() ExpectedAckSeq ..Rtivn Data Retrieving 4.2. ExpectedAck- eto 8.5.6.2] section , ReqSeq au is value This . 31

4 4. Procedures for Flow Control

What remains is the information payload and—just for the first frame of a segmented SDU—the 16 bit SDU length field that preceeds the information payload. Depending on the type of the frame, regarding its position within the SDU, we have to distinguish basically four different cases:

(1) The frame is the first in a sequence of frames that build a complete SDU. This frame is marked with 01 or constant-wise L2CAP_SAR_START in the SAR bits of the control field. When this condition applies the SDU length field is present and the information payload field is reduced by two octets in size.

(2) The frame belongs to a segmented SDU but is neither the first nor the last bit of it. This frame has the bits 11 or constant-wise L2CAP_SAR_CONTINUE set in its SAR bits.

(3) The frame belongs to a segmented SDU and builds the end of it. The SAR bits of its control field are set to 10 or L2CAP_SAR_END.

(4) If the frame is not segmented and builds a SDU by its own, the bits 00 are set in the SAR portion of the control field.

We will now see how these four cases can be worked out in a generic way and how we handle error conditions and exceptions. The first design decision affects handling these different states. Depending on the SAR bits of the control field we differentiate between two explicitly stated cases, namely L2CAP_SAR_UNSEGMENTED and L2CAP_SAR_START and put the other two (the last frame and all continuation frames) into a default case. Receiving an unsegmented frame can be processed straight forward by adjusting the BuerSeq value to be the ExpectedTxSeq one, passing the entire information pay- load to the upper layer and transmitting an S-frame as an acknowledgement to the remote peer. The rest of the function covers the reception of segmented SDUs only. Receiving a start frame requires the SDU length field to be considered and extracted. Building a complete SDU from ground up requires us to have an associated socket buffer avail- able. We declared such a socket buffer in our socket specific structure. The first action to be taken consists of an appropriate error check, because in case we are demanded to build a new SDU from multiple segments but the last reassembling process was not finished correctly, we have to make sure to reset the socket specific SDU buffer. Under normal circumstances we will now allocate enough buffer space for the en- tire SDU and copy the first part of the segmented SDU into the newly allocated buffer. Furthermore the socket bound variable sdu_len is set to the value of the given SDU length minus the length of the first part of the SDU that was just copied into the buffer. This will help us to ensure that we will never accept segments of length bigger than the size of the allocated buffer. Finally the value of BuerSeq is adjusted to the one of ExpectedTxSeq and an S-frame is sent as an acknowledgement.

32 ae lc.Teeitn mlmnainaraycvrdbscLCPmd yin- by mode L2CAP basic covered already called implementation transmission voking layer existing frame of The L2CAP implementation place. the actual takes the in before socket function corresponding handler the for signal a matches l2cap_sock_sendmsg() call This specific socket the userspace. calling by invoked initially is data Sending Data Transmitting 4.3. the to SDU SDU values: entire the the the and reset pass and frame we afterwards, end buffer, buffer filled an corresponding completely the is free a this layer, of upper case terms as In in S-frame complete an peer. now transmit remote is and the accordingly, values to all acknowledgement adjust an buffer, socket SDU the into values, its immediately. function reset buffer, the off socket break corresponding to the and cancel free to process, implementation our reassembling al- causes SDU our This the buffer. in allocated the space ( of length remaining length remaining frame’s no the the is if there applies If condition second checks. ( error buffer two SDU of located consists part first The h ehiu fteeitn mlmnainmksueo ito rget nthe frame. in specific fragments one of for list used a be of to use is makes field length implementation SDU existing no the and the of B- at use, technique uses sequence in The mode check is L2CAP frame frame or Basic a field of layer. control end lower in identical—no the basically way are to the which passed covered frames and differences created Fundamental are frames needs. which the fulfill to approach different fnn fteaoesae ro odtosapyw oyteifrainpayload information the copy we apply conditions error stated above the of none If frames. end and frames continuation of reception the both handles case default The uliga qiaetfntoaiyfrflwcnrlmd eurdacomplete a required mode control flow for functionality equivalent an Building } f( 2A_E_A oto =LCPSRED)&& ) L2CAP_SAR_END == */ ) sdu control ( for )) L2CAP_GET_SAR (( frame buffer_seq -> if last (sk) l2cap_pi /* , (sk l2cap_send_sframe ( if ecy(sbpt(lcpp s)-su,sb-ln,sb-dt k -> skb , ->data skb ->len), skb , ->sdu (sk) l2cap_pi ( skb_put ( memcpy 2a_i(k >bfe_e 2a_i(k >eptsq; exp_txseq -> (sk) l2cap_pi = ->len; skb -= buffer_seq -> (sk) sdu_len l2cap_pi -> (sk) l2cap_pi l2cap_do_send() len); f(sc_uu_c_k s 2a_i(k ->sdu)) (sk) l2cap_pi , (sk sock_queue_rcv_skb ( if eun-6; return 2a_i(k >suln=0; = ; NULL sdu_len -> = (sk) l2cap_pi ->sdu (sk) l2cap_pi fe_k 2a_i(k ->sdu); (sk) l2cap_pi ( kfree_skb sdu_len eie oetpclbscerrcekn oki acquired is lock a checking error basic typical some Besides . ihtemessage the with 2a_i(k >suln= ) { 0)) == sdu_len -> (sk) l2cap_pi ( eun-1; return s0 ebekoftefnto n euna ro.The error. an return and function the off break we 0) is msg steifrainpayload. information the as skb->len scamdt elre than larger be to claimed is ) sendmsg() ..Tasitn Data Transmitting 4.3. ucinfrom function 33

4 4. Procedures for Flow Control socket buffer shared info structure where the entire message is separated into multiple fragments of information payload fields. Instead of rewriting the existing function we decided to split the functionality of segmenting the SDU and building the actual I-frames into two seperate and new functions, called l2cap_segment_sdu() and l2cap_do_send_rfc(). Depending on the connection’s mode, the corresponding control flow takes place: if (l2cap_pi(sk)->mode == L2CAP_MODE_FLOW) { err = l2cap_segment_sdu(sk, msg, len); if (err < 0) goto out; if (l2cap_do_send_rfc(sk) < 0) err = -1; } else { err = l2cap_do_send(sk, msg, len); } The function l2cap_segment_sdu() is the counter-part to the function that handles the reassembling process, l2cap_reassemble_sdu(). At first we store the value of the minimum between the length of the message and the size of the MTU minus the L2CAP header into a variable called count. This variable is needed to keep track of the remaining length of the message that has not yet been put into information payload fields of I-frames. The first part of the function covers the case in which one single I-frame is enough to hold the entire message. This applies whenever the length of the message equals the size of count. In such a case the way to process the I-frame is pretty much straight forward. We allocate enough space for a socket buffer, create the L2CAP header and the individual control field, copy the message from userspace into the buffer via memcpy_fromiovec() and calculate the frame check sequence over the header, the control field and the information payload field. Finally we increase the value of Next- TxSeq by one and store the created socket buffer at the end of a transmit queue. Once we did all these steps we break out of this function immediately. It is a whole different story once we need to send a message that exceeds the size of count. In such a case we need to segment the SDU and create a bunch of individual I-frames. This enforces us to make use of the SAR bits in the control field and use the SDU length field in the very first I-frame. Before we start actually building all the I-frames we adjust the value of count by decreasing it by two bytes and increasing the size of the virtual header’s length by two bytes—this is due to the fact that we need two more bytes for the SDU length field and have therefore two bytes less for the in- formation payload field. Furhter more the SAR bits are initialized to L2CAP_SAR_START. The basic idea on how the segmentation is handled is based on a while loop over the remaining length of the message. The while loop starts with a socket buffer al- location of size count plus the header’s length. After that the header is created and put into the first four bytes of the newly allocated socket buffer. Afterwards the in- dividual control field is created and put at the following two bytes. If this is the first frame in the series of segments (the SAR bits are set to L2CAP_SAR_START), then the next

34 -rmsi u uu,w euu hs nsadps hmt h oe ae by layer lower the to them pass and ones those function. dequeue this exit we invoking we queue, sent, our be in to need I-frames that TxQueue our in the frames subtracting no are by there acknowledged if or been yet not from but sent been have by only not timer. invoked retransmission be a easily of can tion it that so written l2cap_sock_sendmsg was function This transmission. is loop TxQueue, the the ensure to variables some re-adjust to values. have the We valid of with TxQueue. bytes entered the two of last end the the at at put of and value calculated The is buffer. sequence socket check frame the that After field: payload information Now buffer’s SDU. socket the the of into length userspace actual from the with filled are bytes two inta sivkdo h xiaino h oio ie rwti h reassembly the within or timer monitor the of expiration called func- is the ac- The function pure on work. of invoked this purpose is by the that implemented for tion was explicitly functionality S-frames latter using their The by and or knowledgements. I-frames field, using control by the implicitly in values sent be either can Acknowledgements Acknowledgments Sending 4.3.1. u hnvrw r loe osn rmsadw urnl aeoeo more or one have currently we and frames send to allowed are we whenever But variable local a has function The in stored are which I-frames multiple into segmented been has SDU the After NextTxSeq } } f(mmp_rmoe k_u sb,cut) s >mgiv,count , msg_iov -> msg ), count , (skb skb_put */ ( payload memcpy_fromiovec ( if Information /* hl (i- xqeefae )& p >ox cuid) { )) occupied > otxw -> (pi && 0) > tx_queue_frames -> ((pi while ){ )) hci_send_acl() l2cap_do_send_rfc() ftereceiver’s the If . i- xqeefae --; tx_queue_frames -> pi f( r c_edal(on-ho k ) 0) < 0)) , skb , ->hcon (conn hci_send_acl = err (( if ) NULL == (skb if r EAL ; -EFAULT = err k k_euu &i- xqee); tx_queue -> (&pi skb_dequeue = skb oofi ; fail goto cuid++; occupied l2cap_send_sframe() spr fanra rnmsinpoes u lob h expira- the by also but process, transmission normal a of part as : oofi ; fail goto ; fail goto NextTxSeq TxWindow sivkdt culysn h -rmsawaiting I-frames the send actually to invoked is occupied sicesdb n n h oktbfe sput is buffer socket the and one by increased is . sfl ( full is htcmue h au ffae that frames of value the computes that occupied count qastevleof value the equals ..Tasitn Data Transmitting 4.3. ye a ecopied be can bytes ExpectedAckSeq ReqSeq otxw 35 )

4 4. Procedures for Flow Control

S-frames are simple structures. Figure 4.1 illustrates the four different fields, each 16 bits wide, that compose one S-frame. Note that no information payload field is present and we therefore have a fixed length for the entire frame. Building such a frame consists of allocating the necessary socket buffer, creating the L2CAP header and the individual control field. Figure 4.2 illustrates, that the control field for an S-frame in flow control mode consists only of the ReqSeq bits and the last bit which is set to one.3 Finally the frame check sequence is computed over all preceeding bytes and attached to the socket buffer. Then the buffer can be passed to the lower layer by calling hci_send_acl(), and the monitor timer is restarted.

4.3.2. Monitor and Retransmission Timer

The monitor and retransmission timers prevent us of from getting stuck in a deadlock by resending necessary acknowledgement frames to the remote peer, and by trans- mitting I-frames continuously in case sent acknowledgements from the remote peer got lost. The monitor timer will ensure periodic traffic between both peers as long as the connection is held in an open state which keeps sequence numbers synchronized. The monitor timer is of even more interest in retransmission mode where a specific bit can be used for signalling purposes. The retransmission timer on the other hand is used to continue tranmission of I- frames by the sender even if the current monitored TxWindow of the remote’s receiv- ing peer is full. This situation shall prevent us from a deadlock in case either an acknowledgement frame got lost on its way or one of the already sent I-frames was corrupted and could not be acknowledged but does neither occupy a space in the receiver’s TxWindow. Both timers are defined in l2cap_sock_init: init_timer(&l2cap_pi(sk)->ret_timer); l2cap_pi(sk)->ret_timer.function = l2cap_retransmission_timer; l2cap_pi(sk)->ret_timer.data = (unsigned long)l2cap_pi(sk);

init_timer(&l2cap_pi(sk)->mon_timer); l2cap_pi(sk)->mon_timer.function = l2cap_monitor_timer; l2cap_pi(sk)->mon_timer.data = (unsigned long)l2cap_pi(sk); The signal handler l2cap_retransmission_timer increases the value of ExpectedAck- Seq by one and starts the monitor timer in case no more I-frames await transmission. This condition applies whenever ExpectedAckSeq equals NextTxSeq. If there are still I-frames that need to be sent the retransmission timer is started a socket lock is ac- quired and l2cap_do_send_rfc() is called to transmit the next I-frame (this can be done because ExpectedAckSeq is now increased).

3The value of the S bits would have to be implemented in retransmission mode, but this is outside the scope of this work.

36 ihwihte r aldi led ovre ota tcnb oprdt the to compared be can it that so converted already is called kernel’s current are they which with and timer, with peer remote the the by re-acknowledge its received to I-frame S-frame in-sequence an and of valid transmission last inquiring on based is functionality trigbt iesi civdby achieved is timers both Starting called is handler signal timer’s monitor The ReqSeq 2a_tr_o_ie s i- mnt Z/10); 1000) / HZ * imon_to -> pi , (sk l2cap_start_mon_timer au,adfial etr h oio timer. monitor the restart finally and value, l2cap_start_mon_timer jiffies au,e.g.: value, o h oio ie epciey h timeout The respectively. timer monitor the for l2cap_start_ret_timer l2cap_monitor_timer ..Tasitn Data Transmitting 4.3. o h retransmission the for l t minimal its All . ExpectedTxSeq 37 as

4 5. Summary

5.1. Testing and Analysis

The GNU/Linux system is based on a monolithic kernel, and to work inside ker- nelspace is always critical and must be done cautiously. The L2CAP layer of Linux’ Bluetooth subsystem is a seperate module that allows it to be dynamically linked to or removed from the running kernel. But due to the monolithic structure of the kernel itself, a failure in kernelspace, like a NULL pointer dereference, a deadlock or a race condition, can cause fatal exceptions that usually stall the entire system. Debugging in kernel mode can be done in various ways, although none of them is very comfortable and all debugging facilities have their own drawbacks. We didn’t make any use of one of the unofficial kernel debuggers whenever we encountered problems. Instead we used the module’s built-in debugging output with extended printk() statements. This was sufficient as long as we didn’t make any serious faults. And in fact we didn’t encounter any of the more annoying faults like the aforementioned NULL pointer dereferences or equivalent. But one troublemaker stalled the whole devel- opment process for a big amount of time. By changing from one kernel version to another that used the PREEMPT option of the kernel’s configuration to make the ker- nel preemptible, the entire system crashed reproducibly. Difficult enough to locate the error because the system just hangs and the X terminals were not fast enough to catch and print the debugging output. Fortunately the Linux kernel provides its developers the facility to work on the framebuffer console where output is immediately dumped if the console log level is set to an appropriate value.1 To work only with the console can be tricky when the monitor and/or the console’s screen resolution is not big enough to show all neces- sary information on one page because scrolling is not possible and there is no way to copy the messages into any file or onto another computer. This task may be achieved when working with a serial connection but there was no serial connector available on the main development computer. Intensive testing was accomplished in each phase of the implementation. The test- ing environment consisted of two Acer notebooks (Acer Travelmate 803LMiB and

1The Linux kernel offers the so-called SysRq keys, that can be usually accessed by pressing Alt + Print + Function simultaneously, e.g. setting the loglevel to 8 to print all warnings and other non-critical messages.

38 uneo h bec fflwcnrlcpblt nalordvcs nesv etcases test conse- intensive a devices, As our man- all specification. in different capability same from control the flow devices on of ways absence based the many are of how configuration all quence in although the realize behave, during to can behaviour amazing ufactures was specific It device encounter process. layer. L2CAP to the definitely of use helped intensive makes that method easy head- and an kernel. kernel compiled as the respective to used was the dynamically was kernel against module files patched binary module a the L2CAP linked Such own and integrated our ers stable. be built is to we it supposed before once is tree started but plain kernel experimental The main be the to released. into considered were is versions that kernel code tegrates new as accom- time to over used vanilla we changed kernel task The this devices. aforementioned plish the and kernel patched a with response’s the in Mode option. re- L2CAP control Basic by flow pa- for feature, and unacceptable support retransmission control for concrete failure flow only a any indicating with a configure request rameters, to returned configuration appropriate refused also an mobile stubbornly to but it sponding S75 features, though, Siemens Sadly extended the support for ). definitely to support was claimed indicating devices only bitmask, these not all which of phone candidate closest The bitmask: features extended features the extended of field use data to the claimed inside re- Apple bits a and any Toshiba as offer flow not from success did (like ones no but the features stated like extended that Stacks response of control information sult. it— support corresponding flow on about a stack use request mode) software to control oldest information the able an with was on device the venturers returned S55—probably different Siemens from The machines mode. test available the endian little x86 a Intel are uses laptops still machines. the iMac whereas microarchitecture this PowerPC because endian transmission, big data endianess-aware and proper ensure PowerPC. with on (Tiger) shipped 10.4 comes X that OS stack Mac and the system 3.03.13 finally operating versions and implementation Apple’s stack in our Windows XP test Windows for to original stack Toshiba the able the 4.20.01, were ones, we Siemens versions. but two different the considerations, many BTA-6030).against in in (Cellink all stacks adapter take software Bluetooth couldn’t Bluetooth We USB different external multiple an exist and There S75), phones and mobile two S55 adapters, (Siemens Bluetooth integrated with 3002WTMi) Travelmate Acer 2 e Appendix See h etrslsta eahee ihohrdvcswr oeo esueu.They useful. less or more were devices other with achieved we that results test The computer Linux a between files retrieving and sending of consisted cases test The all of none that determination the was enough, frustrating even but to Interesting, us enabled machine test a as use could we that G4 iMac Apple the Especially xeddFaue ak:0 00 00 00 00 00 : Mask Features Extended 2a_nomto_s ye0x02rsl x0iet2 ident 0x00 result x0002 0 type : l2cap_information_rsp enlwspthdwt h fca acsto h le rjc,wihin- which project, BlueZ the of patchset official the with patched was kernel B o ealddsrpino hsprocedure. this of description detailed a for every urnl vial xeddfaue( feature extended available currently ..TsigadAnalysis and Testing 5.1. 2 edn n retrieving and Sending 0x0007 39

5 5. Summary for this last part could not be created. Finally the only tests that worked as expected could be achieved with two patched Linux PCs. L2CAP flow control mode is definitely a nice feature and may be of even more interest in industrial environments which are limited by resource (e.g. only slow embedded processors) or if the device has to handle multiple high bandwidth con- nections under tough conditions like large distances with walls between the devices or similar scenarios. It can be proven that flow control is in action if both the information response and the configuration response are returned with appropriate values.

5.2. Conclusion and Future Work

The implementation of Flow Control Mode for Linux’ Bluetooth L2CAP layer was a major task that significantly enlarged the existing functionality. It was an advantage to work on an existing piece of software that was well written and structured. This prevented the undertaking of writing the code for the entire layer from ground up. Future work may be based at first on finding bugs and improving the code before this part finds its way into the main kernel tree. Besides that, Flow Control Mode for Linux’ L2CAP layer can be considered as being complete. However there is some more work that can be done, that is closely related to this implementation. One part covers the Retransmission Mode that makes use of multiple functions and paradigms that were now already—at least partly—implemented. Retransmission Mode is a very interesting feature to provide users reliable channels. Linux’ L2CAP layer lacks only the lately introduced functionality like Retransmission Mode, Quality of Service Mode, or the Flush Timeout option.

40 in ihnteLnxkernel. Linux the within tions table following The Types Data Architectures' A. al A.1.: Table 1 h opeestfralacietrscnb on n[ in found be can architectures all for set complete The a4I-46 i 8 4 x86_64 4 Bit 64 8 sparc 4 IA-64 ppc 4 Bit 32 m68k StrongARM Arm, Bit 64 ia64 i386 Processor Alpha arm26 arm alpha Architecture pr6 lr-pr 4Bt48 8 4/8 4 4 Bit 64 Bit 64 4 Bit 64 or 32 Ultra-Sparc PPC64 sparc64 MIPS ppc64 mips nysm ftemr oua rhtcue n hi eindifferences design their and architectures popular more the of some Only 1 AMD64/EMT64 Sparc Sun PowerPC 68 Motorola Intel version) (old Arm Description oesacietrldsg ifrne n hi implementa- their and differences design architectural covers x86 xxx 2Bit 32 Bit 32 Word 4Bit 64 Bit 32 Bit 32 Bit 32 ud n Kunst and Quade 4 4 sizeof(int) 4 4 4 4 , 2006 hpe 9.3] Chapter , 4 4 sizeof(long) 8 4 4 4 41

A B. Development Notes

During the time of this development the patches created for testing purposes had to be applied to a recent kernel version with included latest patchsets of Linux’ Blue- tooth maintainer Marcel Holtmann. This means a vanilla kernel like 2.6.17.x had to be patched first of all with the most recent patch of the bluez.org website (e.g. patch- 2.6.17-mh5), before we could create our own patch covering the two files l2cap.c and l2cap.h. The patched vanilla kernel (e.g. linux-2.6.17mh5) had to be compiled. This was done using Ubuntu Dapper Drake 6.06 via the following commands: $ tar xjf linux-2.6.17.tar.bz2 $ cd linux-2.6.17 linux-2.6.17$ patch -p1 < ../patch-2.6.17-mh5 linux-2.6.17$ cp /boot/config-2.6.15-26-686 .config linux-2.6.17$ make oldconfig [...] [edit some config options manually] linux-2.6.17$ fakeroot make-kpkg kernel_image modules_image --initrd --revision mh5 binary [...] linux-2.6.17$ cd .. $ sudo dpkg -i kernel-image-2.6.17mh5_i386.deb After completing this step the new kernel has to be booted. Within this image we can compile and load our L2CAP module dynamically via insmod. The development took place within the directory /home/martin/kernel. To compile the necessary kernel module we used the following Makefile: ifneq ($(KERNELRELEASE),) obj-m := l2cap.o else

modules: l2cap.c $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules

install: l2cap.ko install -d $(DESTDIR)/lib/modules/$(shell uname -r)/kernel/ net/bluetooth

42 h he dpesw sdhddfeethrwr aaiie.Teotu fthe of output The capabilites. hardware different had used command we adapters three The Used Adapters Bluetooth B.1. adapter: Bluetooth the up respect setting and with as unloading running well helped already as that was modules script necessary module shell the small L2CAP reloading a no created sure we Therefore make to dependencies. to had we so, do to command. hr n hw h uptfrteetra eln T-00UBadapter: USB BTA-6030 Cellink the external finally the and for 803LMiB output Travelmate the Acer shows the one cov- of third one adapter second Bluetooth the integrated 3002WTMi, the Travelmate Acer ers the of adapter Bluetooth integrated fn annso rosapae ewr bet odadts h oue But module. the test and load to able were we appeared errors a or issuing warnings by no module If the compiled we Makefile this of help the With ec nt./le tl start utils - .d/bluez init /etc/ stop utils - .d/bluez init /etc/ bash bin/ #!/ c0:Tp USB : Type : hci0 mo l2cap rmmod rfcomm rmmod endif : clean nmd/hm atn/kre 2a .ko l2cap / kernel / martin / home / insmod opoecrc16 modprobe ccni c0up hci0 hciconfig : uninstall bn/dpo -e depmod / sbin / bn/dpo -e depmod / sbin / m-f* o*o* o c.. * m m_esosMdls. Modules tmp_versions . cmd .*. .*.d .c mod *. *.o ko / *. /net kernel -rf -r)/ rm uname shell /$( modules )/lib/ DESTDIR $( -rf rm Xbts:292 c 103 c 0cmad 15err :0 errors :0 :145 64:8 errors commands MTU: :18614 :0 sco events SCO :0 :120935 sco 377:10 acl MTU: :65326 acl :8249626 ACL bytes ISCAN :968409 :27 TX PSCAN bytes B:6B:5F:8E RX 00:0 RUNNING : UP Address BD akttp M M M H H H V V HV3 HV2 HV1 DH5 DH3 DH1 DM5 DM3 DM1 : type Packet ntl m64- ooi.o$ ETI /i oue $ shell /$( modules / )/lib DESTDIR $( .ko nozomi -c 644 -m install etrs:0f xf00 x800 x800 x00 0 0x00 0x08 0x08 0x38 0x0d 0xff 0xff : Features ccni -a hciconfig nm r/kre e/bluetooth net/ / kernel -r)/ uname symvers leot 2a .ko l2cap / bluetooth ssonfraltreaatr.Tefis n saotthe about is one first The adapters. three all for shown is ..ButohAatr Used Adapters Bluetooth B.1. aemodules make 43

B B. Development Notes

Link policy: RSWITCH HOLD SNIFF PARK Link mode: SLAVE ACCEPT Name: 'karin-laptop-0' Class: 0x3e0100 Service Classes: Networking, Rendering, Capturing Device Class: Computer, Uncategorized HCI Ver: 1.2 (0x2) HCI Rev: 0x69 LMP Ver: 1.2 (0x2) LMP Subver: 0x694a Manufacturer: (15)

hci0: Type: USB BD Address: 00:02:8A:9E:93:1D ACL MTU: 192:8 SCO MTU: 64:8 UPRUNNINGPSCANISCAN RX bytes:385 acl:0 sco:0 events:18 errors:0 TX bytes:319 acl:0 sco:0 commands:17 errors:0 Features: 0xff 0xff 0x0f 0x00 0x00 0x00 0x00 0x00 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH HOLD SNIFF PARK Link mode: SLAVE ACCEPT Name: 'bart-0' Class: 0x3e0100 Service Classes: Networking, Rendering, Capturing Device Class: Computer, Uncategorized HCI Ver: 1.1 (0x1) HCI Rev: 0x20d LMP Ver: 1.1 (0x1) LMP Subver: 0x20d Manufacturer: Cambridge Silicon Radio (10)

hci1: Type: USB BD Address: 00:0A:94:02:F2:1F ACL MTU: 384:8 SCO MTU: 64:8 UPRUNNINGPSCANISCAN RX bytes:385 acl:0 sco:0 events:18 errors:0 TX bytes:319 acl:0 sco:0 commands:17 errors:0 Features: 0xff 0xff 0x8f 0xfe 0x9b 0xf9 0x00 0x80 Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3 Link policy: RSWITCH HOLD SNIFF PARK Link mode: SLAVE ACCEPT Name: 'bart-1' Class: 0x3e0100 Service Classes: Networking, Rendering, Capturing Device Class: Computer, Uncategorized HCI Ver: 1.1 (0x1) HCI Rev: 0x7a6 LMP Ver: 1.1 (0x1) LMP Subver: 0x7a6 Manufacturer: Cambridge Silicon Radio (10)

44 Bibliography

Ch. Benvenuti. Understanding Linux Network Internals. O’Reilly, first edition, 2006. ISBN 0-596-00255-6.

BlueSpec. Specification of the Bluetooth System Ver. 2.0+EDR. Bluetooth SIG, November 2004.

D. P. Bovet and M. Cesati. Understanding the Linux Kernel. O’Reilly, third edition, 2006. ISBN 0-596-00565-2.

J. Corbet, A. Rubini, and G. Kroah-Hartman. Linux Device Drivers. O’Reilly, third edition, 2005. ISBN 0-596-00590-3.

R. D. Love. Linux-Kernel-Handbuch. Addison-Wesley, 2005. ISBN 3-8273-2204-9.

J. Quade and E.-K. Kunst. Linux-Treiber entwickeln. dpunkt-Verlag, second edition, 2006. ISBN 3-89864-392-1.

A. S. Tanenbaum. Modern Operating Systems. Prentice Hall, second edition, 2001. ISBN 0-13-031358-0.

A. S. Tanenbaum. Computer Networks. Prentice Hall, fourth edition, 2003. ISBN 0-13- 066102-3.

J. Wollert. Das Bluetooth Handbuch. Franzis Verlag, 2002. ISBN 3-7723-5323-1.

45