• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #pragma once
16 // clang-format off
17 
18 #include <chrono>
19 #include <cstdint>
20 #include <limits>
21 #include <string>
22 
23 #include <pw_chrono/system_clock.h>
24 
25 #include "pw_bluetooth_sapphire/internal/host/common/macros.h"
26 #include "pw_bluetooth_sapphire/internal/host/l2cap/frame_headers.h"
27 
28 namespace bt::l2cap {
29 
30 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. Note that we assume there is no flush timeout
31 // on the underlying logical link.
32 static constexpr auto kErtmReceiverReadyPollTimerDuration = std::chrono::seconds(2);
33 static_assert(kErtmReceiverReadyPollTimerDuration <= std::chrono::milliseconds(std::numeric_limits<uint16_t>::max()));
34 static constexpr uint16_t kErtmReceiverReadyPollTimerMsecs = static_cast<uint16_t>(std::chrono::duration_cast<std::chrono::milliseconds>(kErtmReceiverReadyPollTimerDuration).count());
35 
36 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. Note that we assume there is no flush timeout
37 // on the underlying logical link. If the link _does_ have a flush timeout, then our implementation
38 // will be slower to trigger the monitor timeout than the specification recommends.
39 static constexpr auto kErtmMonitorTimerDuration = std::chrono::seconds(12);
40 static_assert(kErtmMonitorTimerDuration <= std::chrono::milliseconds(std::numeric_limits<uint16_t>::max()));
41 static constexpr uint16_t kErtmMonitorTimerMsecs = static_cast<uint16_t>(std::chrono::duration_cast<std::chrono::milliseconds>(kErtmMonitorTimerDuration).count());
42 
43 // See Core Spec v5.0, Volume 3, Part A, Sec 6.2.1. This is the initial value of the timeout duration.
44 // Although Signaling Channel packets are not sent as automatically flushable, Signaling Channel packets
45 // may not receive a response for reasons other than packet loss (e.g. peer is slow to respond due to pairing).
46 // As such, L2CAP uses the "at least double" back-off scheme to increase this timeout after retransmissions.
47 static constexpr auto kSignalingChannelResponseTimeout = std::chrono::seconds(1);
48 static_assert(kSignalingChannelResponseTimeout >= std::chrono::seconds(1));
49 static_assert(kSignalingChannelResponseTimeout <= std::chrono::seconds(60));
50 
51 // Selected so that total time between initial transmission and last retransmission timout is less
52 // than 60 seconds when using the exponential back-off scheme.
53 static constexpr size_t kMaxSignalingChannelTransmissions = 5;
54 
55 // See Core Spec v5.0, Volume 3, Part A, Sec 6.2.2. This initial value is the only timeout duration
56 // used because Signaling Channel packets are not to be sent as automatically flushable and thus
57 // requests will not be retransmitted at the L2CAP level per its "at least double" back-off scheme.
58 static constexpr auto kSignalingChannelExtendedResponseTimeout = std::chrono::seconds(60);
59 static_assert(kSignalingChannelExtendedResponseTimeout >= std::chrono::seconds(60));
60 static_assert(kSignalingChannelExtendedResponseTimeout <= std::chrono::seconds(300));
61 static constexpr pw::chrono::SystemClock::duration kPwSignalingChannelExtendedResponseTimeout = std::chrono::seconds(60);
62 
63 // L2CAP channel identifier uniquely identifies fixed and connection-oriented
64 // channels over a logical link.
65 // (see Core Spec v5.0, Vol 3, Part A, Section 2.1)
66 using ChannelId = uint16_t;
67 
68 // Null ID, "never be used as a destination endpoint"
69 constexpr ChannelId kInvalidChannelId = 0x0000;
70 
71 // Fixed channel identifiers used in BR/EDR & AMP (i.e. ACL-U, ASB-U, and AMP-U
72 // logical links)
73 constexpr ChannelId kSignalingChannelId = 0x0001;
74 constexpr ChannelId kConnectionlessChannelId = 0x0002;
75 constexpr ChannelId kAMPManagerChannelId = 0x0003;
76 constexpr ChannelId kSMPChannelId = 0x0007;
77 constexpr ChannelId kAMPTestManagerChannelId = 0x003F;
78 
79 // Fixed channel identifiers used in LE
80 constexpr ChannelId kATTChannelId = 0x0004;
81 constexpr ChannelId kLESignalingChannelId = 0x0005;
82 constexpr ChannelId kLESMPChannelId = 0x0006;
83 
84 // Range of dynamic channel identifiers; each logical link has its own set of
85 // channel IDs (except for ACL-U and AMP-U, which share a namespace)
86 // (see Tables 2.1 and 2.2 in v5.0, Vol 3, Part A, Section 2.1)
87 constexpr ChannelId kFirstDynamicChannelId = 0x0040;
88 constexpr ChannelId kLastACLDynamicChannelId = 0xFFFF;
89 constexpr ChannelId kLastLEDynamicChannelId = 0x007F;
90 
91 // Basic L2CAP header. This corresponds to the header used in a B-frame (Basic Information Frame)
92 // and is the basis of all other frame types.
93 struct BasicHeader {
94   uint16_t length;
95   ChannelId channel_id;
96 } __attribute__((packed));
97 
98 // Frame Check Sequence (FCS) footer. This is computed for S- and I-frames per Core Spec v5.0, Vol
99 // 3, Part A, Section 3.3.5.
100 struct FrameCheckSequence {
101   uint16_t fcs;
102 } __attribute__((packed));
103 
104 // Initial state of the FCS generating circuit is all zeroes per v5.0, Vol 3, Part A, Section 3.3.5,
105 // Figure 3.5.
106 constexpr FrameCheckSequence kInitialFcsValue = {0};
107 
108 // The L2CAP MTU defines the maximum SDU size and is asymmetric. The following are the minimum and
109 // default MTU sizes that a L2CAP implementation must support (see Core Spec v5.0, Vol 3, Part A,
110 // Section 5.1).
111 constexpr uint16_t kDefaultMTU = 672;
112 constexpr uint16_t kMinACLMTU = 48;
113 constexpr uint16_t kMinLEMTU = 23;
114 constexpr uint16_t kMaxMTU = 0xFFFF;
115 
116 // The maximum length of a L2CAP B-frame information payload.
117 constexpr uint16_t kMaxBasicFramePayloadSize = 65535;
118 
119 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. This is the minimum permissible value of
120 // "TxWindow size" in the Retransmission & Flow Control Configuration Option.
121 static constexpr uint8_t kErtmMinUnackedInboundFrames = 1;
122 
123 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. We do not have a limit on inbound data that we
124 // can receive in bursts based on memory constraints or other considerations, so this is simply the
125 // maximum permissible value.
126 static constexpr uint8_t kErtmMaxUnackedInboundFrames = 63;
127 
128 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. We rely on the ERTM Monitor Timeout and the
129 // ACL-U Link Supervision Timeout to terminate links based on data loss rather than rely on the peer
130 // to handle unacked ERTM frames in the peer-to-local direction.
131 static constexpr uint8_t kErtmMaxInboundRetransmissions = 0;  // Infinite retransmissions
132 
133 // See Core Spec v5.0, Volume 3, Part A, Sec 8.6.2.1. We can receive as large of a PDU as the peer
134 // can encode and transmit. However, this value is for the information payload field of an I-Frame,
135 // which is bounded by the 16-bit length field together with frame header and footer overhead.
136 static constexpr uint16_t kMaxInboundPduPayloadSize = std::numeric_limits<uint16_t>::max() -
137                                                       sizeof(internal::EnhancedControlField) -
138                                                       sizeof(FrameCheckSequence);
139 
140 // Channel configuration option type field (Core Spec v5.1, Vol 3, Part A, Section 5):
141 enum class OptionType : uint8_t {
142   kMTU = 0x01,
143   kFlushTimeout = 0x02,
144   kQoS = 0x03,
145   kRetransmissionAndFlowControl = 0x04,
146   kFCS = 0x05,
147   kExtendedFlowSpecification = 0x06,
148   kExtendedWindowSize = 0x07,
149 };
150 
151 // Signaling packet formats (Core Spec v5.0, Vol 3, Part A, Section 4):
152 
153 using CommandCode = uint8_t;
154 
155 enum class RejectReason : uint16_t {
156   kNotUnderstood = 0x0000,
157   kSignalingMTUExceeded = 0x0001,
158   kInvalidCID = 0x0002,
159 };
160 
161 // Results field in Connection Response and Create Channel Response
162 enum class ConnectionResult : uint16_t {
163   kSuccess = 0x0000,
164   kPending = 0x0001,
165   kPsmNotSupported = 0x0002,
166   kSecurityBlock = 0x0003,
167   kNoResources = 0x0004,
168   kControllerNotSupported = 0x0005,  // for Create Channel only
169   kInvalidSourceCID = 0x0006,
170   kSourceCIDAlreadyAllocated = 0x0007,
171 };
172 
173 enum class ConnectionStatus : uint16_t {
174   kNoInfoAvailable = 0x0000,
175   kAuthenticationPending = 0x0001,
176   kAuthorizationPending = 0x0002,
177 };
178 
179 // Flags field in Configuration request and response, continuation bit mask
180 constexpr uint16_t kConfigurationContinuation = 0x0001;
181 
182 enum class ConfigurationResult : uint16_t {
183   kSuccess = 0x0000,
184   kUnacceptableParameters = 0x0001,
185   kRejected = 0x0002,
186   kUnknownOptions = 0x0003,
187   kPending = 0x0004,
188   kFlowSpecRejected = 0x0005,
189 };
190 
191 // Channel modes available in a L2CAP_CONFIGURATION_REQ packet. These are not
192 // the full set of possible channel modes, see CreditBasedFlowControlMode.
193 enum class RetransmissionAndFlowControlMode : uint8_t {
194   kBasic = 0x00,
195   kRetransmission = 0x01,
196   kFlowControl = 0x02,
197   kEnhancedRetransmission = 0x03,
198   kStreaming = 0x04,
199 };
200 
201 // FCS Types defined by the specification
202 enum class FcsType : uint8_t {
203   kNoFcs = 0x00,
204   kSixteenBitFcs = 0x01,
205 };
206 
207 // Channel modes defined by an associated channel establishment packet rather
208 // than an L2CAP_CONFIGURATION_REQ packet. The values here are the signaling
209 // packet code of the connection establishment request packet associated with
210 // the mode. These are not the full set of possible channel modes, see
211 // RetransmissionAndFlowControlMode.
212 enum class CreditBasedFlowControlMode : uint8_t {
213   kLeCreditBasedFlowControl = 0x14,
214   kEnhancedCreditBasedFlowControl = 0x17,
215 };
216 
217 enum class InformationType : uint16_t {
218   kConnectionlessMTU = 0x0001,
219   kExtendedFeaturesSupported = 0x0002,
220   kFixedChannelsSupported = 0x0003,
221 };
222 
223 enum class InformationResult : uint16_t {
224   kSuccess = 0x0000,
225   kNotSupported = 0x0001,
226 };
227 
228 // Type and bit masks for Extended Features Supported in the Information
229 // Response data field (Vol 3, Part A, Section 4.12)
230 using ExtendedFeatures = uint32_t;
231 constexpr ExtendedFeatures kExtendedFeaturesBitFlowControl = 1 << 0;
232 constexpr ExtendedFeatures kExtendedFeaturesBitRetransmission = 1 << 1;
233 constexpr ExtendedFeatures kExtendedFeaturesBitBidirectionalQoS = 1 << 2;
234 constexpr ExtendedFeatures kExtendedFeaturesBitEnhancedRetransmission = 1 << 3;
235 constexpr ExtendedFeatures kExtendedFeaturesBitStreaming = 1 << 4;
236 constexpr ExtendedFeatures kExtendedFeaturesBitFCSOption = 1 << 5;
237 constexpr ExtendedFeatures kExtendedFeaturesBitExtendedFlowSpecification = 1 << 6;
238 constexpr ExtendedFeatures kExtendedFeaturesBitFixedChannels = 1 << 7;
239 constexpr ExtendedFeatures kExtendedFeaturesBitExtendedWindowSize = 1 << 8;
240 constexpr ExtendedFeatures kExtendedFeaturesBitUnicastConnectionlessDataRx = 1 << 9;
241 
242 // Type and bit masks for Fixed Channels Supported in the Information Response
243 // data field (Vol 3, Part A, Section 4.12)
244 using FixedChannelsSupported = uint64_t;
245 constexpr FixedChannelsSupported kFixedChannelsSupportedBitNull = 1ULL << 0;
246 constexpr FixedChannelsSupported kFixedChannelsSupportedBitSignaling = 1ULL << 1;
247 constexpr FixedChannelsSupported kFixedChannelsSupportedBitConnectionless = 1ULL << 2;
248 constexpr FixedChannelsSupported kFixedChannelsSupportedBitAMPManager = 1ULL << 3;
249 constexpr FixedChannelsSupported kFixedChannelsSupportedBitATT = 1ULL << 4;
250 constexpr FixedChannelsSupported kFixedChannelsSupportedBitLESignaling = 1ULL << 5;
251 constexpr FixedChannelsSupported kFixedChannelsSupportedBitSMP = 1ULL << 6;
252 constexpr FixedChannelsSupported kFixedChannelsSupportedBitSM = 1ULL << 7;
253 constexpr FixedChannelsSupported kFixedChannelsSupportedBitAMPTestManager = 1ULL << 63;
254 
255 enum class ConnectionParameterUpdateResult : uint16_t {
256   kAccepted = 0x0000,
257   kRejected = 0x0001,
258 };
259 
260 enum class LECreditBasedConnectionResult : uint16_t {
261   kSuccess = 0x0000,
262   kPsmNotSupported = 0x0002,
263   kNoResources = 0x0004,
264   kInsufficientAuthentication = 0x0005,
265   kInsufficientAuthorization = 0x0006,
266   kInsufficientEncryptionKeySize = 0x0007,
267   kInsufficientEncryption = 0x0008,
268   kInvalidSourceCID = 0x0009,
269   kSourceCIDAlreadyAllocated = 0x000A,
270   kUnacceptableParameters = 0x000B,
271 };
272 
273 // Type used for all Protocol and Service Multiplexer (PSM) identifiers,
274 // including those dynamically-assigned/-obtained
275 using Psm = uint16_t;
276 constexpr Psm kInvalidPsm = 0x0000;
277 // The minimum PSM value in the dynamic range of PSMs.
278 // Defined in 5.2, Vol 3, Part A, 4.2.
279 constexpr Psm kMinDynamicPsm = 0x1001;
280 
281 // Well-known Protocol and Service Multiplexer values defined by the Bluetooth
282 // SIG in Logical Link Control Assigned Numbers
283 // https://www.bluetooth.com/specifications/assigned-numbers/logical-link-control
284 constexpr Psm kSDP = 0x0001;
285 constexpr Psm kRFCOMM = 0x0003;
286 constexpr Psm kTCSBIN = 0x0005; // Telephony Control Specification
287 constexpr Psm kTCSBINCordless = 0x0007;
288 constexpr Psm kBNEP = 0x0009; // Bluetooth Network Encapsulation Protocol
289 constexpr Psm kHIDControl = 0x0011; // Human Interface Device
290 constexpr Psm kHIDInteerup = 0x0013; // Human Interface Device
291 constexpr Psm kAVCTP = 0x0017; // Audio/Video Control Transport Protocol
292 constexpr Psm kAVDTP = 0x0019; // Audio/Video Distribution Transport Protocol
293 constexpr Psm kAVCTP_Browse = 0x001B; // Audio/Video Remote Control Profile (Browsing)
294 constexpr Psm kATT = 0x001F; // ATT
295 constexpr Psm k3DSP = 0x0021; // 3D Synchronization Profile
296 constexpr Psm kLE_IPSP = 0x0023; // Internet Protocol Support Profile
297 constexpr Psm kOTS = 0x0025; // Object Transfer Service
298 
299 // Convenience function for visualizing a PSM. Used for Inspect and logging.
300 // Returns string formatted |psm| if not recognized.
PsmToString(l2cap::Psm psm)301 inline std::string PsmToString(l2cap::Psm psm) {
302   switch (psm) {
303     case kInvalidPsm:
304       return "InvalidPsm";
305     case kSDP:
306       return "SDP";
307     case kRFCOMM:
308       return "RFCOMM";
309     case kTCSBIN:
310       return "TCSBIN";
311     case kTCSBINCordless:
312       return "TCSBINCordless";
313     case kBNEP:
314       return "BNEP";
315     case kHIDControl:
316       return "HIDControl";
317     case kHIDInteerup:
318       return "HIDInteerup";
319     case kAVCTP:
320       return "AVCTP";
321     case kAVDTP:
322       return "AVDTP";
323     case kAVCTP_Browse:
324       return "AVCTP_Browse";
325     case kATT:
326       return "ATT";
327     case k3DSP:
328       return "3DSP";
329     case kLE_IPSP:
330       return "LE_IPSP";
331     case kOTS:
332       return "OTS";
333   }
334   return "PSM:" + std::to_string(psm);
335 }
336 
337 // Identifier assigned to each signaling transaction. This is used to match each
338 // signaling channel request with a response.
339 using CommandId = uint8_t;
340 
341 constexpr CommandId kInvalidCommandId = 0x00;
342 
343 // Signaling command header.
344 struct CommandHeader {
345   CommandCode code;
346   CommandId id;
347   uint16_t length;  // Length of the remaining payload
348 } __attribute__((packed));
349 
350 // ACL-U & LE-U
351 constexpr CommandCode kCommandRejectCode = 0x01;
352 constexpr size_t kCommandRejectMaxDataLength = 4;
353 struct CommandRejectPayload {
354   // See RejectReason for possible values.
355   uint16_t reason;
356 
357   // Followed by up to 4 octets of optional data (see Vol 3, Part A, Section 4.1)
358 } __attribute__((packed));
359 
360 // Payload of Command Reject (see Vol 3, Part A, Section 4.1).
361 struct InvalidCIDPayload {
362   // Source CID (relative to rejecter)
363   ChannelId src_cid;
364 
365   // Destination CID (relative to rejecter)
366   ChannelId dst_cid;
367 } __attribute__((packed));
368 
369 // ACL-U
370 constexpr CommandCode kConnectionRequest = 0x02;
371 struct ConnectionRequestPayload {
372   uint16_t psm;
373   ChannelId src_cid;
374 } __attribute__((packed));
375 
376 // ACL-U
377 constexpr CommandCode kConnectionResponse = 0x03;
378 struct ConnectionResponsePayload {
379   ChannelId dst_cid;
380   ChannelId src_cid;
381   ConnectionResult result;
382   ConnectionStatus status;
383 } __attribute__((packed));
384 
385 // ACL-U
386 constexpr CommandCode kConfigurationRequest = 0x04;
387 constexpr size_t kConfigurationOptionMaxDataLength = 22;
388 
389 // Element of configuration payload data (see Vol 3, Part A, Section 5)
390 struct ConfigurationOption {
391   OptionType type;
392   uint8_t length;
393 
394   // Followed by configuration option-specific data
395 } __attribute__((packed));
396 
397 // Payload of Configuration Option (see Vol 3, Part A, Section 5.1)
398 struct MtuOptionPayload {
399   uint16_t mtu;
400 } __attribute__((packed));
401 
402 
403 // Payload of Configuration Option (see Vol 3, Part A, Section 5.2)
404 struct FlushTimeoutOptionPayload {
405   uint16_t flush_timeout;
406 } __attribute__((packed));
407 
408 // Payload of Configuration Option (see Vol 3, Part A, Section 5.4)
409 struct RetransmissionAndFlowControlOptionPayload {
410   RetransmissionAndFlowControlMode mode;
411   uint8_t tx_window_size;
412   uint8_t max_transmit;
413   uint16_t rtx_timeout;
414   uint16_t monitor_timeout;
415   uint16_t mps;
416 } __attribute__((packed));
417 
418 // Payload of the FCS Option (see Vol 3, Part A, Section 5.5)
419 struct FrameCheckSequenceOptionPayload {
420   FcsType fcs_type;
421 } __attribute__((packed));
422 
423 struct ConfigurationRequestPayload {
424   ChannelId dst_cid;
425   uint16_t flags;
426 
427   // Followed by zero or more configuration options of varying length
428 } __attribute__((packed));
429 
430 // ACL-U
431 constexpr CommandCode kConfigurationResponse = 0x05;
432 struct ConfigurationResponsePayload {
433   ChannelId src_cid;
434   uint16_t flags;
435   ConfigurationResult result;
436 
437   // Followed by zero or more configuration options of varying length
438 } __attribute__((packed));
439 
440 // ACL-U & LE-U
441 constexpr CommandCode kDisconnectionRequest = 0x06;
442 struct DisconnectionRequestPayload {
443   ChannelId dst_cid;
444   ChannelId src_cid;
445 } __attribute__((packed));
446 
447 // ACL-U & LE-U
448 constexpr CommandCode kDisconnectionResponse = 0x07;
449 struct DisconnectionResponsePayload {
450   ChannelId dst_cid;
451   ChannelId src_cid;
452 } __attribute__((packed));
453 
454 // ACL-U
455 constexpr CommandCode kEchoRequest = 0x08;
456 
457 // ACL-U
458 constexpr CommandCode kEchoResponse = 0x09;
459 
460 // ACL-U
461 constexpr CommandCode kInformationRequest = 0x0A;
462 struct InformationRequestPayload {
463   InformationType type;
464 } __attribute__((packed));
465 
466 // ACL-U
467 constexpr CommandCode kInformationResponse = 0x0B;
468 constexpr size_t kInformationResponseMaxDataLength = 8;
469 struct InformationResponsePayload {
470   InformationType type;
471   InformationResult result;
472 
473   // Up to 8 octets of optional data (see Vol 3, Part A, Section 4.11)
474 } __attribute__((packed));
475 
476 // LE-U
477 constexpr CommandCode kConnectionParameterUpdateRequest = 0x12;
478 struct ConnectionParameterUpdateRequestPayload {
479   uint16_t interval_min;
480   uint16_t interval_max;
481   uint16_t peripheral_latency;
482   uint16_t timeout_multiplier;
483 } __attribute__((packed));
484 
485 // LE-U
486 constexpr CommandCode kConnectionParameterUpdateResponse = 0x13;
487 struct ConnectionParameterUpdateResponsePayload {
488   ConnectionParameterUpdateResult result;
489 } __attribute__((packed));
490 
491 // LE-U
492 constexpr CommandCode kLECreditBasedConnectionRequest = 0x14;
493 struct LECreditBasedConnectionRequestPayload {
494   uint16_t le_psm;
495   ChannelId src_cid;
496   uint16_t mtu;  // Max. SDU size
497   uint16_t mps;  // Max. PDU size
498   uint16_t initial_credits;
499 } __attribute__((packed));
500 
501 // LE-U
502 constexpr CommandCode kLECreditBasedConnectionResponse = 0x15;
503 struct LECreditBasedConnectionResponsePayload {
504   ChannelId dst_cid;
505   uint16_t mtu;  // Max. SDU size
506   uint16_t mps;  // Max. PDU size
507   uint16_t initial_credits;
508   LECreditBasedConnectionResult result;
509 } __attribute__((packed));
510 
511 // LE-U
512 constexpr CommandCode kLEFlowControlCredit = 0x16;
513 struct LEFlowControlCreditParams {
514   ChannelId cid;
515   uint16_t credits;
516 } __attribute__((packed));
517 
518 }  // namespace bt::l2cap
519 
520