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