xref: /openbmc/linux/net/batman-adv/tp_meter.c (revision d9679d00)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (C) B.A.T.M.A.N. contributors:
3  *
4  * Edo Monticelli, Antonio Quartulli
5  */
6 
7 #include "tp_meter.h"
8 #include "main.h"
9 
10 #include <linux/atomic.h>
11 #include <linux/build_bug.h>
12 #include <linux/byteorder/generic.h>
13 #include <linux/cache.h>
14 #include <linux/compiler.h>
15 #include <linux/err.h>
16 #include <linux/etherdevice.h>
17 #include <linux/gfp.h>
18 #include <linux/if_ether.h>
19 #include <linux/init.h>
20 #include <linux/jiffies.h>
21 #include <linux/kernel.h>
22 #include <linux/kref.h>
23 #include <linux/kthread.h>
24 #include <linux/limits.h>
25 #include <linux/list.h>
26 #include <linux/minmax.h>
27 #include <linux/netdevice.h>
28 #include <linux/param.h>
29 #include <linux/printk.h>
30 #include <linux/random.h>
31 #include <linux/rculist.h>
32 #include <linux/rcupdate.h>
33 #include <linux/sched.h>
34 #include <linux/skbuff.h>
35 #include <linux/slab.h>
36 #include <linux/spinlock.h>
37 #include <linux/stddef.h>
38 #include <linux/string.h>
39 #include <linux/timer.h>
40 #include <linux/wait.h>
41 #include <linux/workqueue.h>
42 #include <uapi/linux/batadv_packet.h>
43 #include <uapi/linux/batman_adv.h>
44 
45 #include "hard-interface.h"
46 #include "log.h"
47 #include "netlink.h"
48 #include "originator.h"
49 #include "send.h"
50 
51 /**
52  * BATADV_TP_DEF_TEST_LENGTH - Default test length if not specified by the user
53  *  in milliseconds
54  */
55 #define BATADV_TP_DEF_TEST_LENGTH 10000
56 
57 /**
58  * BATADV_TP_AWND - Advertised window by the receiver (in bytes)
59  */
60 #define BATADV_TP_AWND 0x20000000
61 
62 /**
63  * BATADV_TP_RECV_TIMEOUT - Receiver activity timeout. If the receiver does not
64  *  get anything for such amount of milliseconds, the connection is killed
65  */
66 #define BATADV_TP_RECV_TIMEOUT 1000
67 
68 /**
69  * BATADV_TP_MAX_RTO - Maximum sender timeout. If the sender RTO gets beyond
70  * such amount of milliseconds, the receiver is considered unreachable and the
71  * connection is killed
72  */
73 #define BATADV_TP_MAX_RTO 30000
74 
75 /**
76  * BATADV_TP_FIRST_SEQ - First seqno of each session. The number is rather high
77  *  in order to immediately trigger a wrap around (test purposes)
78  */
79 #define BATADV_TP_FIRST_SEQ ((u32)-1 - 2000)
80 
81 /**
82  * BATADV_TP_PLEN - length of the payload (data after the batadv_unicast header)
83  *  to simulate
84  */
85 #define BATADV_TP_PLEN (BATADV_TP_PACKET_LEN - ETH_HLEN - \
86 			sizeof(struct batadv_unicast_packet))
87 
88 static u8 batadv_tp_prerandom[4096] __read_mostly;
89 
90 /**
91  * batadv_tp_session_cookie() - generate session cookie based on session ids
92  * @session: TP session identifier
93  * @icmp_uid: icmp pseudo uid of the tp session
94  *
95  * Return: 32 bit tp_meter session cookie
96  */
97 static u32 batadv_tp_session_cookie(const u8 session[2], u8 icmp_uid)
98 {
99 	u32 cookie;
100 
101 	cookie = icmp_uid << 16;
102 	cookie |= session[0] << 8;
103 	cookie |= session[1];
104 
105 	return cookie;
106 }
107 
108 /**
109  * batadv_tp_cwnd() - compute the new cwnd size
110  * @base: base cwnd size value
111  * @increment: the value to add to base to get the new size
112  * @min: minimum cwnd value (usually MSS)
113  *
114  * Return the new cwnd size and ensure it does not exceed the Advertised
115  * Receiver Window size. It is wrapped around safely.
116  * For details refer to Section 3.1 of RFC5681
117  *
118  * Return: new congestion window size in bytes
119  */
120 static u32 batadv_tp_cwnd(u32 base, u32 increment, u32 min)
121 {
122 	u32 new_size = base + increment;
123 
124 	/* check for wrap-around */
125 	if (new_size < base)
126 		new_size = (u32)ULONG_MAX;
127 
128 	new_size = min_t(u32, new_size, BATADV_TP_AWND);
129 
130 	return max_t(u32, new_size, min);
131 }
132 
133 /**
134  * batadv_tp_update_cwnd() - update the Congestion Windows
135  * @tp_vars: the private data of the current TP meter session
136  * @mss: maximum segment size of transmission
137  *
138  * 1) if the session is in Slow Start, the CWND has to be increased by 1
139  * MSS every unique received ACK
140  * 2) if the session is in Congestion Avoidance, the CWND has to be
141  * increased by MSS * MSS / CWND for every unique received ACK
142  */
143 static void batadv_tp_update_cwnd(struct batadv_tp_vars *tp_vars, u32 mss)
144 {
145 	spin_lock_bh(&tp_vars->cwnd_lock);
146 
147 	/* slow start... */
148 	if (tp_vars->cwnd <= tp_vars->ss_threshold) {
149 		tp_vars->dec_cwnd = 0;
150 		tp_vars->cwnd = batadv_tp_cwnd(tp_vars->cwnd, mss, mss);
151 		spin_unlock_bh(&tp_vars->cwnd_lock);
152 		return;
153 	}
154 
155 	/* increment CWND at least of 1 (section 3.1 of RFC5681) */
156 	tp_vars->dec_cwnd += max_t(u32, 1U << 3,
157 				   ((mss * mss) << 6) / (tp_vars->cwnd << 3));
158 	if (tp_vars->dec_cwnd < (mss << 3)) {
159 		spin_unlock_bh(&tp_vars->cwnd_lock);
160 		return;
161 	}
162 
163 	tp_vars->cwnd = batadv_tp_cwnd(tp_vars->cwnd, mss, mss);
164 	tp_vars->dec_cwnd = 0;
165 
166 	spin_unlock_bh(&tp_vars->cwnd_lock);
167 }
168 
169 /**
170  * batadv_tp_update_rto() - calculate new retransmission timeout
171  * @tp_vars: the private data of the current TP meter session
172  * @new_rtt: new roundtrip time in msec
173  */
174 static void batadv_tp_update_rto(struct batadv_tp_vars *tp_vars,
175 				 u32 new_rtt)
176 {
177 	long m = new_rtt;
178 
179 	/* RTT update
180 	 * Details in Section 2.2 and 2.3 of RFC6298
181 	 *
182 	 * It's tricky to understand. Don't lose hair please.
183 	 * Inspired by tcp_rtt_estimator() tcp_input.c
184 	 */
185 	if (tp_vars->srtt != 0) {
186 		m -= (tp_vars->srtt >> 3); /* m is now error in rtt est */
187 		tp_vars->srtt += m; /* rtt = 7/8 srtt + 1/8 new */
188 		if (m < 0)
189 			m = -m;
190 
191 		m -= (tp_vars->rttvar >> 2);
192 		tp_vars->rttvar += m; /* mdev ~= 3/4 rttvar + 1/4 new */
193 	} else {
194 		/* first measure getting in */
195 		tp_vars->srtt = m << 3;	/* take the measured time to be srtt */
196 		tp_vars->rttvar = m << 1; /* new_rtt / 2 */
197 	}
198 
199 	/* rto = srtt + 4 * rttvar.
200 	 * rttvar is scaled by 4, therefore doesn't need to be multiplied
201 	 */
202 	tp_vars->rto = (tp_vars->srtt >> 3) + tp_vars->rttvar;
203 }
204 
205 /**
206  * batadv_tp_batctl_notify() - send client status result to client
207  * @reason: reason for tp meter session stop
208  * @dst: destination of tp_meter session
209  * @bat_priv: the bat priv with all the soft interface information
210  * @start_time: start of transmission in jiffies
211  * @total_sent: bytes acked to the receiver
212  * @cookie: cookie of tp_meter session
213  */
214 static void batadv_tp_batctl_notify(enum batadv_tp_meter_reason reason,
215 				    const u8 *dst, struct batadv_priv *bat_priv,
216 				    unsigned long start_time, u64 total_sent,
217 				    u32 cookie)
218 {
219 	u32 test_time;
220 	u8 result;
221 	u32 total_bytes;
222 
223 	if (!batadv_tp_is_error(reason)) {
224 		result = BATADV_TP_REASON_COMPLETE;
225 		test_time = jiffies_to_msecs(jiffies - start_time);
226 		total_bytes = total_sent;
227 	} else {
228 		result = reason;
229 		test_time = 0;
230 		total_bytes = 0;
231 	}
232 
233 	batadv_netlink_tpmeter_notify(bat_priv, dst, result, test_time,
234 				      total_bytes, cookie);
235 }
236 
237 /**
238  * batadv_tp_batctl_error_notify() - send client error result to client
239  * @reason: reason for tp meter session stop
240  * @dst: destination of tp_meter session
241  * @bat_priv: the bat priv with all the soft interface information
242  * @cookie: cookie of tp_meter session
243  */
244 static void batadv_tp_batctl_error_notify(enum batadv_tp_meter_reason reason,
245 					  const u8 *dst,
246 					  struct batadv_priv *bat_priv,
247 					  u32 cookie)
248 {
249 	batadv_tp_batctl_notify(reason, dst, bat_priv, 0, 0, cookie);
250 }
251 
252 /**
253  * batadv_tp_list_find() - find a tp_vars object in the global list
254  * @bat_priv: the bat priv with all the soft interface information
255  * @dst: the other endpoint MAC address to look for
256  *
257  * Look for a tp_vars object matching dst as end_point and return it after
258  * having increment the refcounter. Return NULL is not found
259  *
260  * Return: matching tp_vars or NULL when no tp_vars with @dst was found
261  */
262 static struct batadv_tp_vars *batadv_tp_list_find(struct batadv_priv *bat_priv,
263 						  const u8 *dst)
264 {
265 	struct batadv_tp_vars *pos, *tp_vars = NULL;
266 
267 	rcu_read_lock();
268 	hlist_for_each_entry_rcu(pos, &bat_priv->tp_list, list) {
269 		if (!batadv_compare_eth(pos->other_end, dst))
270 			continue;
271 
272 		/* most of the time this function is invoked during the normal
273 		 * process..it makes sens to pay more when the session is
274 		 * finished and to speed the process up during the measurement
275 		 */
276 		if (unlikely(!kref_get_unless_zero(&pos->refcount)))
277 			continue;
278 
279 		tp_vars = pos;
280 		break;
281 	}
282 	rcu_read_unlock();
283 
284 	return tp_vars;
285 }
286 
287 /**
288  * batadv_tp_list_find_session() - find tp_vars session object in the global
289  *  list
290  * @bat_priv: the bat priv with all the soft interface information
291  * @dst: the other endpoint MAC address to look for
292  * @session: session identifier
293  *
294  * Look for a tp_vars object matching dst as end_point, session as tp meter
295  * session and return it after having increment the refcounter. Return NULL
296  * is not found
297  *
298  * Return: matching tp_vars or NULL when no tp_vars was found
299  */
300 static struct batadv_tp_vars *
301 batadv_tp_list_find_session(struct batadv_priv *bat_priv, const u8 *dst,
302 			    const u8 *session)
303 {
304 	struct batadv_tp_vars *pos, *tp_vars = NULL;
305 
306 	rcu_read_lock();
307 	hlist_for_each_entry_rcu(pos, &bat_priv->tp_list, list) {
308 		if (!batadv_compare_eth(pos->other_end, dst))
309 			continue;
310 
311 		if (memcmp(pos->session, session, sizeof(pos->session)) != 0)
312 			continue;
313 
314 		/* most of the time this function is invoked during the normal
315 		 * process..it makes sense to pay more when the session is
316 		 * finished and to speed the process up during the measurement
317 		 */
318 		if (unlikely(!kref_get_unless_zero(&pos->refcount)))
319 			continue;
320 
321 		tp_vars = pos;
322 		break;
323 	}
324 	rcu_read_unlock();
325 
326 	return tp_vars;
327 }
328 
329 /**
330  * batadv_tp_vars_release() - release batadv_tp_vars from lists and queue for
331  *  free after rcu grace period
332  * @ref: kref pointer of the batadv_tp_vars
333  */
334 static void batadv_tp_vars_release(struct kref *ref)
335 {
336 	struct batadv_tp_vars *tp_vars;
337 	struct batadv_tp_unacked *un, *safe;
338 
339 	tp_vars = container_of(ref, struct batadv_tp_vars, refcount);
340 
341 	/* lock should not be needed because this object is now out of any
342 	 * context!
343 	 */
344 	spin_lock_bh(&tp_vars->unacked_lock);
345 	list_for_each_entry_safe(un, safe, &tp_vars->unacked_list, list) {
346 		list_del(&un->list);
347 		kfree(un);
348 	}
349 	spin_unlock_bh(&tp_vars->unacked_lock);
350 
351 	kfree_rcu(tp_vars, rcu);
352 }
353 
354 /**
355  * batadv_tp_vars_put() - decrement the batadv_tp_vars refcounter and possibly
356  *  release it
357  * @tp_vars: the private data of the current TP meter session to be free'd
358  */
359 static void batadv_tp_vars_put(struct batadv_tp_vars *tp_vars)
360 {
361 	if (!tp_vars)
362 		return;
363 
364 	kref_put(&tp_vars->refcount, batadv_tp_vars_release);
365 }
366 
367 /**
368  * batadv_tp_sender_cleanup() - cleanup sender data and drop and timer
369  * @bat_priv: the bat priv with all the soft interface information
370  * @tp_vars: the private data of the current TP meter session to cleanup
371  */
372 static void batadv_tp_sender_cleanup(struct batadv_priv *bat_priv,
373 				     struct batadv_tp_vars *tp_vars)
374 {
375 	cancel_delayed_work(&tp_vars->finish_work);
376 
377 	spin_lock_bh(&tp_vars->bat_priv->tp_list_lock);
378 	hlist_del_rcu(&tp_vars->list);
379 	spin_unlock_bh(&tp_vars->bat_priv->tp_list_lock);
380 
381 	/* drop list reference */
382 	batadv_tp_vars_put(tp_vars);
383 
384 	atomic_dec(&tp_vars->bat_priv->tp_num);
385 
386 	/* kill the timer and remove its reference */
387 	del_timer_sync(&tp_vars->timer);
388 	/* the worker might have rearmed itself therefore we kill it again. Note
389 	 * that if the worker should run again before invoking the following
390 	 * del_timer(), it would not re-arm itself once again because the status
391 	 * is OFF now
392 	 */
393 	del_timer(&tp_vars->timer);
394 	batadv_tp_vars_put(tp_vars);
395 }
396 
397 /**
398  * batadv_tp_sender_end() - print info about ended session and inform client
399  * @bat_priv: the bat priv with all the soft interface information
400  * @tp_vars: the private data of the current TP meter session
401  */
402 static void batadv_tp_sender_end(struct batadv_priv *bat_priv,
403 				 struct batadv_tp_vars *tp_vars)
404 {
405 	u32 session_cookie;
406 
407 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
408 		   "Test towards %pM finished..shutting down (reason=%d)\n",
409 		   tp_vars->other_end, tp_vars->reason);
410 
411 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
412 		   "Last timing stats: SRTT=%ums RTTVAR=%ums RTO=%ums\n",
413 		   tp_vars->srtt >> 3, tp_vars->rttvar >> 2, tp_vars->rto);
414 
415 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
416 		   "Final values: cwnd=%u ss_threshold=%u\n",
417 		   tp_vars->cwnd, tp_vars->ss_threshold);
418 
419 	session_cookie = batadv_tp_session_cookie(tp_vars->session,
420 						  tp_vars->icmp_uid);
421 
422 	batadv_tp_batctl_notify(tp_vars->reason,
423 				tp_vars->other_end,
424 				bat_priv,
425 				tp_vars->start_time,
426 				atomic64_read(&tp_vars->tot_sent),
427 				session_cookie);
428 }
429 
430 /**
431  * batadv_tp_sender_shutdown() - let sender thread/timer stop gracefully
432  * @tp_vars: the private data of the current TP meter session
433  * @reason: reason for tp meter session stop
434  */
435 static void batadv_tp_sender_shutdown(struct batadv_tp_vars *tp_vars,
436 				      enum batadv_tp_meter_reason reason)
437 {
438 	if (!atomic_dec_and_test(&tp_vars->sending))
439 		return;
440 
441 	tp_vars->reason = reason;
442 }
443 
444 /**
445  * batadv_tp_sender_finish() - stop sender session after test_length was reached
446  * @work: delayed work reference of the related tp_vars
447  */
448 static void batadv_tp_sender_finish(struct work_struct *work)
449 {
450 	struct delayed_work *delayed_work;
451 	struct batadv_tp_vars *tp_vars;
452 
453 	delayed_work = to_delayed_work(work);
454 	tp_vars = container_of(delayed_work, struct batadv_tp_vars,
455 			       finish_work);
456 
457 	batadv_tp_sender_shutdown(tp_vars, BATADV_TP_REASON_COMPLETE);
458 }
459 
460 /**
461  * batadv_tp_reset_sender_timer() - reschedule the sender timer
462  * @tp_vars: the private TP meter data for this session
463  *
464  * Reschedule the timer using tp_vars->rto as delay
465  */
466 static void batadv_tp_reset_sender_timer(struct batadv_tp_vars *tp_vars)
467 {
468 	/* most of the time this function is invoked while normal packet
469 	 * reception...
470 	 */
471 	if (unlikely(atomic_read(&tp_vars->sending) == 0))
472 		/* timer ref will be dropped in batadv_tp_sender_cleanup */
473 		return;
474 
475 	mod_timer(&tp_vars->timer, jiffies + msecs_to_jiffies(tp_vars->rto));
476 }
477 
478 /**
479  * batadv_tp_sender_timeout() - timer that fires in case of packet loss
480  * @t: address to timer_list inside tp_vars
481  *
482  * If fired it means that there was packet loss.
483  * Switch to Slow Start, set the ss_threshold to half of the current cwnd and
484  * reset the cwnd to 3*MSS
485  */
486 static void batadv_tp_sender_timeout(struct timer_list *t)
487 {
488 	struct batadv_tp_vars *tp_vars = from_timer(tp_vars, t, timer);
489 	struct batadv_priv *bat_priv = tp_vars->bat_priv;
490 
491 	if (atomic_read(&tp_vars->sending) == 0)
492 		return;
493 
494 	/* if the user waited long enough...shutdown the test */
495 	if (unlikely(tp_vars->rto >= BATADV_TP_MAX_RTO)) {
496 		batadv_tp_sender_shutdown(tp_vars,
497 					  BATADV_TP_REASON_DST_UNREACHABLE);
498 		return;
499 	}
500 
501 	/* RTO exponential backoff
502 	 * Details in Section 5.5 of RFC6298
503 	 */
504 	tp_vars->rto <<= 1;
505 
506 	spin_lock_bh(&tp_vars->cwnd_lock);
507 
508 	tp_vars->ss_threshold = tp_vars->cwnd >> 1;
509 	if (tp_vars->ss_threshold < BATADV_TP_PLEN * 2)
510 		tp_vars->ss_threshold = BATADV_TP_PLEN * 2;
511 
512 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
513 		   "Meter: RTO fired during test towards %pM! cwnd=%u new ss_thr=%u, resetting last_sent to %u\n",
514 		   tp_vars->other_end, tp_vars->cwnd, tp_vars->ss_threshold,
515 		   atomic_read(&tp_vars->last_acked));
516 
517 	tp_vars->cwnd = BATADV_TP_PLEN * 3;
518 
519 	spin_unlock_bh(&tp_vars->cwnd_lock);
520 
521 	/* resend the non-ACKed packets.. */
522 	tp_vars->last_sent = atomic_read(&tp_vars->last_acked);
523 	wake_up(&tp_vars->more_bytes);
524 
525 	batadv_tp_reset_sender_timer(tp_vars);
526 }
527 
528 /**
529  * batadv_tp_fill_prerandom() - Fill buffer with prefetched random bytes
530  * @tp_vars: the private TP meter data for this session
531  * @buf: Buffer to fill with bytes
532  * @nbytes: amount of pseudorandom bytes
533  */
534 static void batadv_tp_fill_prerandom(struct batadv_tp_vars *tp_vars,
535 				     u8 *buf, size_t nbytes)
536 {
537 	u32 local_offset;
538 	size_t bytes_inbuf;
539 	size_t to_copy;
540 	size_t pos = 0;
541 
542 	spin_lock_bh(&tp_vars->prerandom_lock);
543 	local_offset = tp_vars->prerandom_offset;
544 	tp_vars->prerandom_offset += nbytes;
545 	tp_vars->prerandom_offset %= sizeof(batadv_tp_prerandom);
546 	spin_unlock_bh(&tp_vars->prerandom_lock);
547 
548 	while (nbytes) {
549 		local_offset %= sizeof(batadv_tp_prerandom);
550 		bytes_inbuf = sizeof(batadv_tp_prerandom) - local_offset;
551 		to_copy = min(nbytes, bytes_inbuf);
552 
553 		memcpy(&buf[pos], &batadv_tp_prerandom[local_offset], to_copy);
554 		pos += to_copy;
555 		nbytes -= to_copy;
556 		local_offset = 0;
557 	}
558 }
559 
560 /**
561  * batadv_tp_send_msg() - send a single message
562  * @tp_vars: the private TP meter data for this session
563  * @src: source mac address
564  * @orig_node: the originator of the destination
565  * @seqno: sequence number of this packet
566  * @len: length of the entire packet
567  * @session: session identifier
568  * @uid: local ICMP "socket" index
569  * @timestamp: timestamp in jiffies which is replied in ack
570  *
571  * Create and send a single TP Meter message.
572  *
573  * Return: 0 on success, BATADV_TP_REASON_DST_UNREACHABLE if the destination is
574  * not reachable, BATADV_TP_REASON_MEMORY_ERROR if the packet couldn't be
575  * allocated
576  */
577 static int batadv_tp_send_msg(struct batadv_tp_vars *tp_vars, const u8 *src,
578 			      struct batadv_orig_node *orig_node,
579 			      u32 seqno, size_t len, const u8 *session,
580 			      int uid, u32 timestamp)
581 {
582 	struct batadv_icmp_tp_packet *icmp;
583 	struct sk_buff *skb;
584 	int r;
585 	u8 *data;
586 	size_t data_len;
587 
588 	skb = netdev_alloc_skb_ip_align(NULL, len + ETH_HLEN);
589 	if (unlikely(!skb))
590 		return BATADV_TP_REASON_MEMORY_ERROR;
591 
592 	skb_reserve(skb, ETH_HLEN);
593 	icmp = skb_put(skb, sizeof(*icmp));
594 
595 	/* fill the icmp header */
596 	ether_addr_copy(icmp->dst, orig_node->orig);
597 	ether_addr_copy(icmp->orig, src);
598 	icmp->version = BATADV_COMPAT_VERSION;
599 	icmp->packet_type = BATADV_ICMP;
600 	icmp->ttl = BATADV_TTL;
601 	icmp->msg_type = BATADV_TP;
602 	icmp->uid = uid;
603 
604 	icmp->subtype = BATADV_TP_MSG;
605 	memcpy(icmp->session, session, sizeof(icmp->session));
606 	icmp->seqno = htonl(seqno);
607 	icmp->timestamp = htonl(timestamp);
608 
609 	data_len = len - sizeof(*icmp);
610 	data = skb_put(skb, data_len);
611 	batadv_tp_fill_prerandom(tp_vars, data, data_len);
612 
613 	r = batadv_send_skb_to_orig(skb, orig_node, NULL);
614 	if (r == NET_XMIT_SUCCESS)
615 		return 0;
616 
617 	return BATADV_TP_REASON_CANT_SEND;
618 }
619 
620 /**
621  * batadv_tp_recv_ack() - ACK receiving function
622  * @bat_priv: the bat priv with all the soft interface information
623  * @skb: the buffer containing the received packet
624  *
625  * Process a received TP ACK packet
626  */
627 static void batadv_tp_recv_ack(struct batadv_priv *bat_priv,
628 			       const struct sk_buff *skb)
629 {
630 	struct batadv_hard_iface *primary_if = NULL;
631 	struct batadv_orig_node *orig_node = NULL;
632 	const struct batadv_icmp_tp_packet *icmp;
633 	struct batadv_tp_vars *tp_vars;
634 	const unsigned char *dev_addr;
635 	size_t packet_len, mss;
636 	u32 rtt, recv_ack, cwnd;
637 
638 	packet_len = BATADV_TP_PLEN;
639 	mss = BATADV_TP_PLEN;
640 	packet_len += sizeof(struct batadv_unicast_packet);
641 
642 	icmp = (struct batadv_icmp_tp_packet *)skb->data;
643 
644 	/* find the tp_vars */
645 	tp_vars = batadv_tp_list_find_session(bat_priv, icmp->orig,
646 					      icmp->session);
647 	if (unlikely(!tp_vars))
648 		return;
649 
650 	if (unlikely(atomic_read(&tp_vars->sending) == 0))
651 		goto out;
652 
653 	/* old ACK? silently drop it.. */
654 	if (batadv_seq_before(ntohl(icmp->seqno),
655 			      (u32)atomic_read(&tp_vars->last_acked)))
656 		goto out;
657 
658 	primary_if = batadv_primary_if_get_selected(bat_priv);
659 	if (unlikely(!primary_if))
660 		goto out;
661 
662 	orig_node = batadv_orig_hash_find(bat_priv, icmp->orig);
663 	if (unlikely(!orig_node))
664 		goto out;
665 
666 	/* update RTO with the new sampled RTT, if any */
667 	rtt = jiffies_to_msecs(jiffies) - ntohl(icmp->timestamp);
668 	if (icmp->timestamp && rtt)
669 		batadv_tp_update_rto(tp_vars, rtt);
670 
671 	/* ACK for new data... reset the timer */
672 	batadv_tp_reset_sender_timer(tp_vars);
673 
674 	recv_ack = ntohl(icmp->seqno);
675 
676 	/* check if this ACK is a duplicate */
677 	if (atomic_read(&tp_vars->last_acked) == recv_ack) {
678 		atomic_inc(&tp_vars->dup_acks);
679 		if (atomic_read(&tp_vars->dup_acks) != 3)
680 			goto out;
681 
682 		if (recv_ack >= tp_vars->recover)
683 			goto out;
684 
685 		/* if this is the third duplicate ACK do Fast Retransmit */
686 		batadv_tp_send_msg(tp_vars, primary_if->net_dev->dev_addr,
687 				   orig_node, recv_ack, packet_len,
688 				   icmp->session, icmp->uid,
689 				   jiffies_to_msecs(jiffies));
690 
691 		spin_lock_bh(&tp_vars->cwnd_lock);
692 
693 		/* Fast Recovery */
694 		tp_vars->fast_recovery = true;
695 		/* Set recover to the last outstanding seqno when Fast Recovery
696 		 * is entered. RFC6582, Section 3.2, step 1
697 		 */
698 		tp_vars->recover = tp_vars->last_sent;
699 		tp_vars->ss_threshold = tp_vars->cwnd >> 1;
700 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
701 			   "Meter: Fast Recovery, (cur cwnd=%u) ss_thr=%u last_sent=%u recv_ack=%u\n",
702 			   tp_vars->cwnd, tp_vars->ss_threshold,
703 			   tp_vars->last_sent, recv_ack);
704 		tp_vars->cwnd = batadv_tp_cwnd(tp_vars->ss_threshold, 3 * mss,
705 					       mss);
706 		tp_vars->dec_cwnd = 0;
707 		tp_vars->last_sent = recv_ack;
708 
709 		spin_unlock_bh(&tp_vars->cwnd_lock);
710 	} else {
711 		/* count the acked data */
712 		atomic64_add(recv_ack - atomic_read(&tp_vars->last_acked),
713 			     &tp_vars->tot_sent);
714 		/* reset the duplicate ACKs counter */
715 		atomic_set(&tp_vars->dup_acks, 0);
716 
717 		if (tp_vars->fast_recovery) {
718 			/* partial ACK */
719 			if (batadv_seq_before(recv_ack, tp_vars->recover)) {
720 				/* this is another hole in the window. React
721 				 * immediately as specified by NewReno (see
722 				 * Section 3.2 of RFC6582 for details)
723 				 */
724 				dev_addr = primary_if->net_dev->dev_addr;
725 				batadv_tp_send_msg(tp_vars, dev_addr,
726 						   orig_node, recv_ack,
727 						   packet_len, icmp->session,
728 						   icmp->uid,
729 						   jiffies_to_msecs(jiffies));
730 				tp_vars->cwnd = batadv_tp_cwnd(tp_vars->cwnd,
731 							       mss, mss);
732 			} else {
733 				tp_vars->fast_recovery = false;
734 				/* set cwnd to the value of ss_threshold at the
735 				 * moment that Fast Recovery was entered.
736 				 * RFC6582, Section 3.2, step 3
737 				 */
738 				cwnd = batadv_tp_cwnd(tp_vars->ss_threshold, 0,
739 						      mss);
740 				tp_vars->cwnd = cwnd;
741 			}
742 			goto move_twnd;
743 		}
744 
745 		if (recv_ack - atomic_read(&tp_vars->last_acked) >= mss)
746 			batadv_tp_update_cwnd(tp_vars, mss);
747 move_twnd:
748 		/* move the Transmit Window */
749 		atomic_set(&tp_vars->last_acked, recv_ack);
750 	}
751 
752 	wake_up(&tp_vars->more_bytes);
753 out:
754 	batadv_hardif_put(primary_if);
755 	batadv_orig_node_put(orig_node);
756 	batadv_tp_vars_put(tp_vars);
757 }
758 
759 /**
760  * batadv_tp_avail() - check if congestion window is not full
761  * @tp_vars: the private data of the current TP meter session
762  * @payload_len: size of the payload of a single message
763  *
764  * Return: true when congestion window is not full, false otherwise
765  */
766 static bool batadv_tp_avail(struct batadv_tp_vars *tp_vars,
767 			    size_t payload_len)
768 {
769 	u32 win_left, win_limit;
770 
771 	win_limit = atomic_read(&tp_vars->last_acked) + tp_vars->cwnd;
772 	win_left = win_limit - tp_vars->last_sent;
773 
774 	return win_left >= payload_len;
775 }
776 
777 /**
778  * batadv_tp_wait_available() - wait until congestion window becomes free or
779  *  timeout is reached
780  * @tp_vars: the private data of the current TP meter session
781  * @plen: size of the payload of a single message
782  *
783  * Return: 0 if the condition evaluated to false after the timeout elapsed,
784  *  1 if the condition evaluated to true after the timeout elapsed, the
785  *  remaining jiffies (at least 1) if the condition evaluated to true before
786  *  the timeout elapsed, or -ERESTARTSYS if it was interrupted by a signal.
787  */
788 static int batadv_tp_wait_available(struct batadv_tp_vars *tp_vars, size_t plen)
789 {
790 	int ret;
791 
792 	ret = wait_event_interruptible_timeout(tp_vars->more_bytes,
793 					       batadv_tp_avail(tp_vars, plen),
794 					       HZ / 10);
795 
796 	return ret;
797 }
798 
799 /**
800  * batadv_tp_send() - main sending thread of a tp meter session
801  * @arg: address of the related tp_vars
802  *
803  * Return: nothing, this function never returns
804  */
805 static int batadv_tp_send(void *arg)
806 {
807 	struct batadv_tp_vars *tp_vars = arg;
808 	struct batadv_priv *bat_priv = tp_vars->bat_priv;
809 	struct batadv_hard_iface *primary_if = NULL;
810 	struct batadv_orig_node *orig_node = NULL;
811 	size_t payload_len, packet_len;
812 	int err = 0;
813 
814 	if (unlikely(tp_vars->role != BATADV_TP_SENDER)) {
815 		err = BATADV_TP_REASON_DST_UNREACHABLE;
816 		tp_vars->reason = err;
817 		goto out;
818 	}
819 
820 	orig_node = batadv_orig_hash_find(bat_priv, tp_vars->other_end);
821 	if (unlikely(!orig_node)) {
822 		err = BATADV_TP_REASON_DST_UNREACHABLE;
823 		tp_vars->reason = err;
824 		goto out;
825 	}
826 
827 	primary_if = batadv_primary_if_get_selected(bat_priv);
828 	if (unlikely(!primary_if)) {
829 		err = BATADV_TP_REASON_DST_UNREACHABLE;
830 		tp_vars->reason = err;
831 		goto out;
832 	}
833 
834 	/* assume that all the hard_interfaces have a correctly
835 	 * configured MTU, so use the soft_iface MTU as MSS.
836 	 * This might not be true and in that case the fragmentation
837 	 * should be used.
838 	 * Now, try to send the packet as it is
839 	 */
840 	payload_len = BATADV_TP_PLEN;
841 	BUILD_BUG_ON(sizeof(struct batadv_icmp_tp_packet) > BATADV_TP_PLEN);
842 
843 	batadv_tp_reset_sender_timer(tp_vars);
844 
845 	/* queue the worker in charge of terminating the test */
846 	queue_delayed_work(batadv_event_workqueue, &tp_vars->finish_work,
847 			   msecs_to_jiffies(tp_vars->test_length));
848 
849 	while (atomic_read(&tp_vars->sending) != 0) {
850 		if (unlikely(!batadv_tp_avail(tp_vars, payload_len))) {
851 			batadv_tp_wait_available(tp_vars, payload_len);
852 			continue;
853 		}
854 
855 		/* to emulate normal unicast traffic, add to the payload len
856 		 * the size of the unicast header
857 		 */
858 		packet_len = payload_len + sizeof(struct batadv_unicast_packet);
859 
860 		err = batadv_tp_send_msg(tp_vars, primary_if->net_dev->dev_addr,
861 					 orig_node, tp_vars->last_sent,
862 					 packet_len,
863 					 tp_vars->session, tp_vars->icmp_uid,
864 					 jiffies_to_msecs(jiffies));
865 
866 		/* something went wrong during the preparation/transmission */
867 		if (unlikely(err && err != BATADV_TP_REASON_CANT_SEND)) {
868 			batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
869 				   "Meter: %s() cannot send packets (%d)\n",
870 				   __func__, err);
871 			/* ensure nobody else tries to stop the thread now */
872 			if (atomic_dec_and_test(&tp_vars->sending))
873 				tp_vars->reason = err;
874 			break;
875 		}
876 
877 		/* right-shift the TWND */
878 		if (!err)
879 			tp_vars->last_sent += payload_len;
880 
881 		cond_resched();
882 	}
883 
884 out:
885 	batadv_hardif_put(primary_if);
886 	batadv_orig_node_put(orig_node);
887 
888 	batadv_tp_sender_end(bat_priv, tp_vars);
889 	batadv_tp_sender_cleanup(bat_priv, tp_vars);
890 
891 	batadv_tp_vars_put(tp_vars);
892 
893 	return 0;
894 }
895 
896 /**
897  * batadv_tp_start_kthread() - start new thread which manages the tp meter
898  *  sender
899  * @tp_vars: the private data of the current TP meter session
900  */
901 static void batadv_tp_start_kthread(struct batadv_tp_vars *tp_vars)
902 {
903 	struct task_struct *kthread;
904 	struct batadv_priv *bat_priv = tp_vars->bat_priv;
905 	u32 session_cookie;
906 
907 	kref_get(&tp_vars->refcount);
908 	kthread = kthread_create(batadv_tp_send, tp_vars, "kbatadv_tp_meter");
909 	if (IS_ERR(kthread)) {
910 		session_cookie = batadv_tp_session_cookie(tp_vars->session,
911 							  tp_vars->icmp_uid);
912 		pr_err("batadv: cannot create tp meter kthread\n");
913 		batadv_tp_batctl_error_notify(BATADV_TP_REASON_MEMORY_ERROR,
914 					      tp_vars->other_end,
915 					      bat_priv, session_cookie);
916 
917 		/* drop reserved reference for kthread */
918 		batadv_tp_vars_put(tp_vars);
919 
920 		/* cleanup of failed tp meter variables */
921 		batadv_tp_sender_cleanup(bat_priv, tp_vars);
922 		return;
923 	}
924 
925 	wake_up_process(kthread);
926 }
927 
928 /**
929  * batadv_tp_start() - start a new tp meter session
930  * @bat_priv: the bat priv with all the soft interface information
931  * @dst: the receiver MAC address
932  * @test_length: test length in milliseconds
933  * @cookie: session cookie
934  */
935 void batadv_tp_start(struct batadv_priv *bat_priv, const u8 *dst,
936 		     u32 test_length, u32 *cookie)
937 {
938 	struct batadv_tp_vars *tp_vars;
939 	u8 session_id[2];
940 	u8 icmp_uid;
941 	u32 session_cookie;
942 
943 	get_random_bytes(session_id, sizeof(session_id));
944 	get_random_bytes(&icmp_uid, 1);
945 	session_cookie = batadv_tp_session_cookie(session_id, icmp_uid);
946 	*cookie = session_cookie;
947 
948 	/* look for an already existing test towards this node */
949 	spin_lock_bh(&bat_priv->tp_list_lock);
950 	tp_vars = batadv_tp_list_find(bat_priv, dst);
951 	if (tp_vars) {
952 		spin_unlock_bh(&bat_priv->tp_list_lock);
953 		batadv_tp_vars_put(tp_vars);
954 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
955 			   "Meter: test to or from the same node already ongoing, aborting\n");
956 		batadv_tp_batctl_error_notify(BATADV_TP_REASON_ALREADY_ONGOING,
957 					      dst, bat_priv, session_cookie);
958 		return;
959 	}
960 
961 	if (!atomic_add_unless(&bat_priv->tp_num, 1, BATADV_TP_MAX_NUM)) {
962 		spin_unlock_bh(&bat_priv->tp_list_lock);
963 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
964 			   "Meter: too many ongoing sessions, aborting (SEND)\n");
965 		batadv_tp_batctl_error_notify(BATADV_TP_REASON_TOO_MANY, dst,
966 					      bat_priv, session_cookie);
967 		return;
968 	}
969 
970 	tp_vars = kmalloc(sizeof(*tp_vars), GFP_ATOMIC);
971 	if (!tp_vars) {
972 		spin_unlock_bh(&bat_priv->tp_list_lock);
973 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
974 			   "Meter: %s cannot allocate list elements\n",
975 			   __func__);
976 		batadv_tp_batctl_error_notify(BATADV_TP_REASON_MEMORY_ERROR,
977 					      dst, bat_priv, session_cookie);
978 		return;
979 	}
980 
981 	/* initialize tp_vars */
982 	ether_addr_copy(tp_vars->other_end, dst);
983 	kref_init(&tp_vars->refcount);
984 	tp_vars->role = BATADV_TP_SENDER;
985 	atomic_set(&tp_vars->sending, 1);
986 	memcpy(tp_vars->session, session_id, sizeof(session_id));
987 	tp_vars->icmp_uid = icmp_uid;
988 
989 	tp_vars->last_sent = BATADV_TP_FIRST_SEQ;
990 	atomic_set(&tp_vars->last_acked, BATADV_TP_FIRST_SEQ);
991 	tp_vars->fast_recovery = false;
992 	tp_vars->recover = BATADV_TP_FIRST_SEQ;
993 
994 	/* initialise the CWND to 3*MSS (Section 3.1 in RFC5681).
995 	 * For batman-adv the MSS is the size of the payload received by the
996 	 * soft_interface, hence its MTU
997 	 */
998 	tp_vars->cwnd = BATADV_TP_PLEN * 3;
999 	/* at the beginning initialise the SS threshold to the biggest possible
1000 	 * window size, hence the AWND size
1001 	 */
1002 	tp_vars->ss_threshold = BATADV_TP_AWND;
1003 
1004 	/* RTO initial value is 3 seconds.
1005 	 * Details in Section 2.1 of RFC6298
1006 	 */
1007 	tp_vars->rto = 1000;
1008 	tp_vars->srtt = 0;
1009 	tp_vars->rttvar = 0;
1010 
1011 	atomic64_set(&tp_vars->tot_sent, 0);
1012 
1013 	kref_get(&tp_vars->refcount);
1014 	timer_setup(&tp_vars->timer, batadv_tp_sender_timeout, 0);
1015 
1016 	tp_vars->bat_priv = bat_priv;
1017 	tp_vars->start_time = jiffies;
1018 
1019 	init_waitqueue_head(&tp_vars->more_bytes);
1020 
1021 	spin_lock_init(&tp_vars->unacked_lock);
1022 	INIT_LIST_HEAD(&tp_vars->unacked_list);
1023 
1024 	spin_lock_init(&tp_vars->cwnd_lock);
1025 
1026 	tp_vars->prerandom_offset = 0;
1027 	spin_lock_init(&tp_vars->prerandom_lock);
1028 
1029 	kref_get(&tp_vars->refcount);
1030 	hlist_add_head_rcu(&tp_vars->list, &bat_priv->tp_list);
1031 	spin_unlock_bh(&bat_priv->tp_list_lock);
1032 
1033 	tp_vars->test_length = test_length;
1034 	if (!tp_vars->test_length)
1035 		tp_vars->test_length = BATADV_TP_DEF_TEST_LENGTH;
1036 
1037 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1038 		   "Meter: starting throughput meter towards %pM (length=%ums)\n",
1039 		   dst, test_length);
1040 
1041 	/* init work item for finished tp tests */
1042 	INIT_DELAYED_WORK(&tp_vars->finish_work, batadv_tp_sender_finish);
1043 
1044 	/* start tp kthread. This way the write() call issued from userspace can
1045 	 * happily return and avoid to block
1046 	 */
1047 	batadv_tp_start_kthread(tp_vars);
1048 
1049 	/* don't return reference to new tp_vars */
1050 	batadv_tp_vars_put(tp_vars);
1051 }
1052 
1053 /**
1054  * batadv_tp_stop() - stop currently running tp meter session
1055  * @bat_priv: the bat priv with all the soft interface information
1056  * @dst: the receiver MAC address
1057  * @return_value: reason for tp meter session stop
1058  */
1059 void batadv_tp_stop(struct batadv_priv *bat_priv, const u8 *dst,
1060 		    u8 return_value)
1061 {
1062 	struct batadv_orig_node *orig_node;
1063 	struct batadv_tp_vars *tp_vars;
1064 
1065 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1066 		   "Meter: stopping test towards %pM\n", dst);
1067 
1068 	orig_node = batadv_orig_hash_find(bat_priv, dst);
1069 	if (!orig_node)
1070 		return;
1071 
1072 	tp_vars = batadv_tp_list_find(bat_priv, orig_node->orig);
1073 	if (!tp_vars) {
1074 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1075 			   "Meter: trying to interrupt an already over connection\n");
1076 		goto out;
1077 	}
1078 
1079 	batadv_tp_sender_shutdown(tp_vars, return_value);
1080 	batadv_tp_vars_put(tp_vars);
1081 out:
1082 	batadv_orig_node_put(orig_node);
1083 }
1084 
1085 /**
1086  * batadv_tp_reset_receiver_timer() - reset the receiver shutdown timer
1087  * @tp_vars: the private data of the current TP meter session
1088  *
1089  * start the receiver shutdown timer or reset it if already started
1090  */
1091 static void batadv_tp_reset_receiver_timer(struct batadv_tp_vars *tp_vars)
1092 {
1093 	mod_timer(&tp_vars->timer,
1094 		  jiffies + msecs_to_jiffies(BATADV_TP_RECV_TIMEOUT));
1095 }
1096 
1097 /**
1098  * batadv_tp_receiver_shutdown() - stop a tp meter receiver when timeout is
1099  *  reached without received ack
1100  * @t: address to timer_list inside tp_vars
1101  */
1102 static void batadv_tp_receiver_shutdown(struct timer_list *t)
1103 {
1104 	struct batadv_tp_vars *tp_vars = from_timer(tp_vars, t, timer);
1105 	struct batadv_tp_unacked *un, *safe;
1106 	struct batadv_priv *bat_priv;
1107 
1108 	bat_priv = tp_vars->bat_priv;
1109 
1110 	/* if there is recent activity rearm the timer */
1111 	if (!batadv_has_timed_out(tp_vars->last_recv_time,
1112 				  BATADV_TP_RECV_TIMEOUT)) {
1113 		/* reset the receiver shutdown timer */
1114 		batadv_tp_reset_receiver_timer(tp_vars);
1115 		return;
1116 	}
1117 
1118 	batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1119 		   "Shutting down for inactivity (more than %dms) from %pM\n",
1120 		   BATADV_TP_RECV_TIMEOUT, tp_vars->other_end);
1121 
1122 	spin_lock_bh(&tp_vars->bat_priv->tp_list_lock);
1123 	hlist_del_rcu(&tp_vars->list);
1124 	spin_unlock_bh(&tp_vars->bat_priv->tp_list_lock);
1125 
1126 	/* drop list reference */
1127 	batadv_tp_vars_put(tp_vars);
1128 
1129 	atomic_dec(&bat_priv->tp_num);
1130 
1131 	spin_lock_bh(&tp_vars->unacked_lock);
1132 	list_for_each_entry_safe(un, safe, &tp_vars->unacked_list, list) {
1133 		list_del(&un->list);
1134 		kfree(un);
1135 	}
1136 	spin_unlock_bh(&tp_vars->unacked_lock);
1137 
1138 	/* drop reference of timer */
1139 	batadv_tp_vars_put(tp_vars);
1140 }
1141 
1142 /**
1143  * batadv_tp_send_ack() - send an ACK packet
1144  * @bat_priv: the bat priv with all the soft interface information
1145  * @dst: the mac address of the destination originator
1146  * @seq: the sequence number to ACK
1147  * @timestamp: the timestamp to echo back in the ACK
1148  * @session: session identifier
1149  * @socket_index: local ICMP socket identifier
1150  *
1151  * Return: 0 on success, a positive integer representing the reason of the
1152  * failure otherwise
1153  */
1154 static int batadv_tp_send_ack(struct batadv_priv *bat_priv, const u8 *dst,
1155 			      u32 seq, __be32 timestamp, const u8 *session,
1156 			      int socket_index)
1157 {
1158 	struct batadv_hard_iface *primary_if = NULL;
1159 	struct batadv_orig_node *orig_node;
1160 	struct batadv_icmp_tp_packet *icmp;
1161 	struct sk_buff *skb;
1162 	int r, ret;
1163 
1164 	orig_node = batadv_orig_hash_find(bat_priv, dst);
1165 	if (unlikely(!orig_node)) {
1166 		ret = BATADV_TP_REASON_DST_UNREACHABLE;
1167 		goto out;
1168 	}
1169 
1170 	primary_if = batadv_primary_if_get_selected(bat_priv);
1171 	if (unlikely(!primary_if)) {
1172 		ret = BATADV_TP_REASON_DST_UNREACHABLE;
1173 		goto out;
1174 	}
1175 
1176 	skb = netdev_alloc_skb_ip_align(NULL, sizeof(*icmp) + ETH_HLEN);
1177 	if (unlikely(!skb)) {
1178 		ret = BATADV_TP_REASON_MEMORY_ERROR;
1179 		goto out;
1180 	}
1181 
1182 	skb_reserve(skb, ETH_HLEN);
1183 	icmp = skb_put(skb, sizeof(*icmp));
1184 	icmp->packet_type = BATADV_ICMP;
1185 	icmp->version = BATADV_COMPAT_VERSION;
1186 	icmp->ttl = BATADV_TTL;
1187 	icmp->msg_type = BATADV_TP;
1188 	ether_addr_copy(icmp->dst, orig_node->orig);
1189 	ether_addr_copy(icmp->orig, primary_if->net_dev->dev_addr);
1190 	icmp->uid = socket_index;
1191 
1192 	icmp->subtype = BATADV_TP_ACK;
1193 	memcpy(icmp->session, session, sizeof(icmp->session));
1194 	icmp->seqno = htonl(seq);
1195 	icmp->timestamp = timestamp;
1196 
1197 	/* send the ack */
1198 	r = batadv_send_skb_to_orig(skb, orig_node, NULL);
1199 	if (unlikely(r < 0) || r == NET_XMIT_DROP) {
1200 		ret = BATADV_TP_REASON_DST_UNREACHABLE;
1201 		goto out;
1202 	}
1203 	ret = 0;
1204 
1205 out:
1206 	batadv_orig_node_put(orig_node);
1207 	batadv_hardif_put(primary_if);
1208 
1209 	return ret;
1210 }
1211 
1212 /**
1213  * batadv_tp_handle_out_of_order() - store an out of order packet
1214  * @tp_vars: the private data of the current TP meter session
1215  * @skb: the buffer containing the received packet
1216  *
1217  * Store the out of order packet in the unacked list for late processing. This
1218  * packets are kept in this list so that they can be ACKed at once as soon as
1219  * all the previous packets have been received
1220  *
1221  * Return: true if the packed has been successfully processed, false otherwise
1222  */
1223 static bool batadv_tp_handle_out_of_order(struct batadv_tp_vars *tp_vars,
1224 					  const struct sk_buff *skb)
1225 {
1226 	const struct batadv_icmp_tp_packet *icmp;
1227 	struct batadv_tp_unacked *un, *new;
1228 	u32 payload_len;
1229 	bool added = false;
1230 
1231 	new = kmalloc(sizeof(*new), GFP_ATOMIC);
1232 	if (unlikely(!new))
1233 		return false;
1234 
1235 	icmp = (struct batadv_icmp_tp_packet *)skb->data;
1236 
1237 	new->seqno = ntohl(icmp->seqno);
1238 	payload_len = skb->len - sizeof(struct batadv_unicast_packet);
1239 	new->len = payload_len;
1240 
1241 	spin_lock_bh(&tp_vars->unacked_lock);
1242 	/* if the list is empty immediately attach this new object */
1243 	if (list_empty(&tp_vars->unacked_list)) {
1244 		list_add(&new->list, &tp_vars->unacked_list);
1245 		goto out;
1246 	}
1247 
1248 	/* otherwise loop over the list and either drop the packet because this
1249 	 * is a duplicate or store it at the right position.
1250 	 *
1251 	 * The iteration is done in the reverse way because it is likely that
1252 	 * the last received packet (the one being processed now) has a bigger
1253 	 * seqno than all the others already stored.
1254 	 */
1255 	list_for_each_entry_reverse(un, &tp_vars->unacked_list, list) {
1256 		/* check for duplicates */
1257 		if (new->seqno == un->seqno) {
1258 			if (new->len > un->len)
1259 				un->len = new->len;
1260 			kfree(new);
1261 			added = true;
1262 			break;
1263 		}
1264 
1265 		/* look for the right position */
1266 		if (batadv_seq_before(new->seqno, un->seqno))
1267 			continue;
1268 
1269 		/* as soon as an entry having a bigger seqno is found, the new
1270 		 * one is attached _after_ it. In this way the list is kept in
1271 		 * ascending order
1272 		 */
1273 		list_add_tail(&new->list, &un->list);
1274 		added = true;
1275 		break;
1276 	}
1277 
1278 	/* received packet with smallest seqno out of order; add it to front */
1279 	if (!added)
1280 		list_add(&new->list, &tp_vars->unacked_list);
1281 
1282 out:
1283 	spin_unlock_bh(&tp_vars->unacked_lock);
1284 
1285 	return true;
1286 }
1287 
1288 /**
1289  * batadv_tp_ack_unordered() - update number received bytes in current stream
1290  *  without gaps
1291  * @tp_vars: the private data of the current TP meter session
1292  */
1293 static void batadv_tp_ack_unordered(struct batadv_tp_vars *tp_vars)
1294 {
1295 	struct batadv_tp_unacked *un, *safe;
1296 	u32 to_ack;
1297 
1298 	/* go through the unacked packet list and possibly ACK them as
1299 	 * well
1300 	 */
1301 	spin_lock_bh(&tp_vars->unacked_lock);
1302 	list_for_each_entry_safe(un, safe, &tp_vars->unacked_list, list) {
1303 		/* the list is ordered, therefore it is possible to stop as soon
1304 		 * there is a gap between the last acked seqno and the seqno of
1305 		 * the packet under inspection
1306 		 */
1307 		if (batadv_seq_before(tp_vars->last_recv, un->seqno))
1308 			break;
1309 
1310 		to_ack = un->seqno + un->len - tp_vars->last_recv;
1311 
1312 		if (batadv_seq_before(tp_vars->last_recv, un->seqno + un->len))
1313 			tp_vars->last_recv += to_ack;
1314 
1315 		list_del(&un->list);
1316 		kfree(un);
1317 	}
1318 	spin_unlock_bh(&tp_vars->unacked_lock);
1319 }
1320 
1321 /**
1322  * batadv_tp_init_recv() - return matching or create new receiver tp_vars
1323  * @bat_priv: the bat priv with all the soft interface information
1324  * @icmp: received icmp tp msg
1325  *
1326  * Return: corresponding tp_vars or NULL on errors
1327  */
1328 static struct batadv_tp_vars *
1329 batadv_tp_init_recv(struct batadv_priv *bat_priv,
1330 		    const struct batadv_icmp_tp_packet *icmp)
1331 {
1332 	struct batadv_tp_vars *tp_vars;
1333 
1334 	spin_lock_bh(&bat_priv->tp_list_lock);
1335 	tp_vars = batadv_tp_list_find_session(bat_priv, icmp->orig,
1336 					      icmp->session);
1337 	if (tp_vars)
1338 		goto out_unlock;
1339 
1340 	if (!atomic_add_unless(&bat_priv->tp_num, 1, BATADV_TP_MAX_NUM)) {
1341 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1342 			   "Meter: too many ongoing sessions, aborting (RECV)\n");
1343 		goto out_unlock;
1344 	}
1345 
1346 	tp_vars = kmalloc(sizeof(*tp_vars), GFP_ATOMIC);
1347 	if (!tp_vars)
1348 		goto out_unlock;
1349 
1350 	ether_addr_copy(tp_vars->other_end, icmp->orig);
1351 	tp_vars->role = BATADV_TP_RECEIVER;
1352 	memcpy(tp_vars->session, icmp->session, sizeof(tp_vars->session));
1353 	tp_vars->last_recv = BATADV_TP_FIRST_SEQ;
1354 	tp_vars->bat_priv = bat_priv;
1355 	kref_init(&tp_vars->refcount);
1356 
1357 	spin_lock_init(&tp_vars->unacked_lock);
1358 	INIT_LIST_HEAD(&tp_vars->unacked_list);
1359 
1360 	kref_get(&tp_vars->refcount);
1361 	hlist_add_head_rcu(&tp_vars->list, &bat_priv->tp_list);
1362 
1363 	kref_get(&tp_vars->refcount);
1364 	timer_setup(&tp_vars->timer, batadv_tp_receiver_shutdown, 0);
1365 
1366 	batadv_tp_reset_receiver_timer(tp_vars);
1367 
1368 out_unlock:
1369 	spin_unlock_bh(&bat_priv->tp_list_lock);
1370 
1371 	return tp_vars;
1372 }
1373 
1374 /**
1375  * batadv_tp_recv_msg() - process a single data message
1376  * @bat_priv: the bat priv with all the soft interface information
1377  * @skb: the buffer containing the received packet
1378  *
1379  * Process a received TP MSG packet
1380  */
1381 static void batadv_tp_recv_msg(struct batadv_priv *bat_priv,
1382 			       const struct sk_buff *skb)
1383 {
1384 	const struct batadv_icmp_tp_packet *icmp;
1385 	struct batadv_tp_vars *tp_vars;
1386 	size_t packet_size;
1387 	u32 seqno;
1388 
1389 	icmp = (struct batadv_icmp_tp_packet *)skb->data;
1390 
1391 	seqno = ntohl(icmp->seqno);
1392 	/* check if this is the first seqno. This means that if the
1393 	 * first packet is lost, the tp meter does not work anymore!
1394 	 */
1395 	if (seqno == BATADV_TP_FIRST_SEQ) {
1396 		tp_vars = batadv_tp_init_recv(bat_priv, icmp);
1397 		if (!tp_vars) {
1398 			batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1399 				   "Meter: seqno != BATADV_TP_FIRST_SEQ cannot initiate connection\n");
1400 			goto out;
1401 		}
1402 	} else {
1403 		tp_vars = batadv_tp_list_find_session(bat_priv, icmp->orig,
1404 						      icmp->session);
1405 		if (!tp_vars) {
1406 			batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1407 				   "Unexpected packet from %pM!\n",
1408 				   icmp->orig);
1409 			goto out;
1410 		}
1411 	}
1412 
1413 	if (unlikely(tp_vars->role != BATADV_TP_RECEIVER)) {
1414 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1415 			   "Meter: dropping packet: not expected (role=%u)\n",
1416 			   tp_vars->role);
1417 		goto out;
1418 	}
1419 
1420 	tp_vars->last_recv_time = jiffies;
1421 
1422 	/* if the packet is a duplicate, it may be the case that an ACK has been
1423 	 * lost. Resend the ACK
1424 	 */
1425 	if (batadv_seq_before(seqno, tp_vars->last_recv))
1426 		goto send_ack;
1427 
1428 	/* if the packet is out of order enqueue it */
1429 	if (ntohl(icmp->seqno) != tp_vars->last_recv) {
1430 		/* exit immediately (and do not send any ACK) if the packet has
1431 		 * not been enqueued correctly
1432 		 */
1433 		if (!batadv_tp_handle_out_of_order(tp_vars, skb))
1434 			goto out;
1435 
1436 		/* send a duplicate ACK */
1437 		goto send_ack;
1438 	}
1439 
1440 	/* if everything was fine count the ACKed bytes */
1441 	packet_size = skb->len - sizeof(struct batadv_unicast_packet);
1442 	tp_vars->last_recv += packet_size;
1443 
1444 	/* check if this ordered message filled a gap.... */
1445 	batadv_tp_ack_unordered(tp_vars);
1446 
1447 send_ack:
1448 	/* send the ACK. If the received packet was out of order, the ACK that
1449 	 * is going to be sent is a duplicate (the sender will count them and
1450 	 * possibly enter Fast Retransmit as soon as it has reached 3)
1451 	 */
1452 	batadv_tp_send_ack(bat_priv, icmp->orig, tp_vars->last_recv,
1453 			   icmp->timestamp, icmp->session, icmp->uid);
1454 out:
1455 	batadv_tp_vars_put(tp_vars);
1456 }
1457 
1458 /**
1459  * batadv_tp_meter_recv() - main TP Meter receiving function
1460  * @bat_priv: the bat priv with all the soft interface information
1461  * @skb: the buffer containing the received packet
1462  */
1463 void batadv_tp_meter_recv(struct batadv_priv *bat_priv, struct sk_buff *skb)
1464 {
1465 	struct batadv_icmp_tp_packet *icmp;
1466 
1467 	icmp = (struct batadv_icmp_tp_packet *)skb->data;
1468 
1469 	switch (icmp->subtype) {
1470 	case BATADV_TP_MSG:
1471 		batadv_tp_recv_msg(bat_priv, skb);
1472 		break;
1473 	case BATADV_TP_ACK:
1474 		batadv_tp_recv_ack(bat_priv, skb);
1475 		break;
1476 	default:
1477 		batadv_dbg(BATADV_DBG_TP_METER, bat_priv,
1478 			   "Received unknown TP Metric packet type %u\n",
1479 			   icmp->subtype);
1480 	}
1481 	consume_skb(skb);
1482 }
1483 
1484 /**
1485  * batadv_tp_meter_init() - initialize global tp_meter structures
1486  */
1487 void __init batadv_tp_meter_init(void)
1488 {
1489 	get_random_bytes(batadv_tp_prerandom, sizeof(batadv_tp_prerandom));
1490 }
1491