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