1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "l2cap/internal/scheduler_fifo.h"
18 
19 #include "dynamic_channel_impl.h"
20 #include "l2cap/internal/data_pipeline_manager.h"
21 #include "l2cap/l2cap_packets.h"
22 #include "os/log.h"
23 
24 namespace bluetooth {
25 namespace l2cap {
26 namespace internal {
27 
28 Fifo::Fifo(DataPipelineManager* data_pipeline_manager, LowerQueueUpEnd* link_queue_up_end, os::Handler* handler)
29     : data_pipeline_manager_(data_pipeline_manager), link_queue_up_end_(link_queue_up_end), handler_(handler) {
30   ASSERT(link_queue_up_end_ != nullptr && handler_ != nullptr);
31 }
32 
33 Fifo::~Fifo() {
34   if (link_queue_enqueue_registered_) {
35     link_queue_up_end_->UnregisterEnqueue();
36   }
37 }
38 
39 void Fifo::OnPacketsReady(Cid cid, int number_packets) {
40   if (number_packets == 0) {
41     return;
42   }
43   next_to_dequeue_and_num_packets.push(std::make_pair(cid, number_packets));
44   try_register_link_queue_enqueue();
45 }
46 
47 std::unique_ptr<Fifo::UpperDequeue> Fifo::link_queue_enqueue_callback() {
48   ASSERT(!next_to_dequeue_and_num_packets.empty());
49   auto& channel_id_and_number_packets = next_to_dequeue_and_num_packets.front();
50   auto channel_id = channel_id_and_number_packets.first;
51   channel_id_and_number_packets.second--;
52   if (channel_id_and_number_packets.second == 0) {
53     next_to_dequeue_and_num_packets.pop();
54   }
55   auto packet = data_pipeline_manager_->GetDataController(channel_id)->GetNextPacket();
56 
57   data_pipeline_manager_->OnPacketSent(channel_id);
58   if (next_to_dequeue_and_num_packets.empty()) {
59     link_queue_up_end_->UnregisterEnqueue();
60     link_queue_enqueue_registered_ = false;
61   }
62   return packet;
63 }
64 
65 void Fifo::try_register_link_queue_enqueue() {
66   if (link_queue_enqueue_registered_) {
67     return;
68   }
69   link_queue_up_end_->RegisterEnqueue(handler_,
70                                       common::Bind(&Fifo::link_queue_enqueue_callback, common::Unretained(this)));
71   link_queue_enqueue_registered_ = true;
72 }
73 
74 }  // namespace internal
75 }  // namespace l2cap
76 }  // namespace bluetooth
77