1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * NET3: Garbage Collector For AF_UNIX sockets
4 *
5 * Garbage Collector:
6 * Copyright (C) Barak A. Pearlmutter.
7 *
8 * Chopped about by Alan Cox 22/3/96 to make it fit the AF_UNIX socket problem.
9 * If it doesn't work blame me, it worked when Barak sent it.
10 *
11 * Assumptions:
12 *
13 * - object w/ a bit
14 * - free list
15 *
16 * Current optimizations:
17 *
18 * - explicit stack instead of recursion
19 * - tail recurse on first born instead of immediate push/pop
20 * - we gather the stuff that should not be killed into tree
21 * and stack is just a path from root to the current pointer.
22 *
23 * Future optimizations:
24 *
25 * - don't just push entire root set; process in place
26 *
27 * Fixes:
28 * Alan Cox 07 Sept 1997 Vmalloc internal stack as needed.
29 * Cope with changing max_files.
30 * Al Viro 11 Oct 1998
31 * Graph may have cycles. That is, we can send the descriptor
32 * of foo to bar and vice versa. Current code chokes on that.
33 * Fix: move SCM_RIGHTS ones into the separate list and then
34 * skb_free() them all instead of doing explicit fput's.
35 * Another problem: since fput() may block somebody may
36 * create a new unix_socket when we are in the middle of sweep
37 * phase. Fix: revert the logic wrt MARKED. Mark everything
38 * upon the beginning and unmark non-junk ones.
39 *
40 * [12 Oct 1998] AAARGH! New code purges all SCM_RIGHTS
41 * sent to connect()'ed but still not accept()'ed sockets.
42 * Fixed. Old code had slightly different problem here:
43 * extra fput() in situation when we passed the descriptor via
44 * such socket and closed it (descriptor). That would happen on
45 * each unix_gc() until the accept(). Since the struct file in
46 * question would go to the free list and might be reused...
47 * That might be the reason of random oopses on filp_close()
48 * in unrelated processes.
49 *
50 * AV 28 Feb 1999
51 * Kill the explicit allocation of stack. Now we keep the tree
52 * with root in dummy + pointer (gc_current) to one of the nodes.
53 * Stack is represented as path from gc_current to dummy. Unmark
54 * now means "add to tree". Push == "make it a son of gc_current".
55 * Pop == "move gc_current to parent". We keep only pointers to
56 * parents (->gc_tree).
57 * AV 1 Mar 1999
58 * Damn. Added missing check for ->dead in listen queues scanning.
59 *
60 * Miklos Szeredi 25 Jun 2007
61 * Reimplement with a cycle collecting algorithm. This should
62 * solve several problems with the previous code, like being racy
63 * wrt receive and holding up unrelated socket operations.
64 */
65
66 #include <linux/fs.h>
67 #include <linux/list.h>
68 #include <linux/skbuff.h>
69 #include <linux/socket.h>
70 #include <linux/workqueue.h>
71 #include <net/af_unix.h>
72 #include <net/scm.h>
73 #include <net/tcp_states.h>
74
75 #include "af_unix.h"
76
77 struct unix_vertex {
78 struct list_head edges;
79 struct list_head entry;
80 struct list_head scc_entry;
81 unsigned long out_degree;
82 unsigned long index;
83 unsigned long scc_index;
84 };
85
86 struct unix_edge {
87 struct unix_sock *predecessor;
88 struct unix_sock *successor;
89 struct list_head vertex_entry;
90 struct list_head stack_entry;
91 };
92
unix_get_socket(struct file * filp)93 struct unix_sock *unix_get_socket(struct file *filp)
94 {
95 struct inode *inode = file_inode(filp);
96
97 /* Socket ? */
98 if (S_ISSOCK(inode->i_mode) && !(filp->f_mode & FMODE_PATH)) {
99 struct socket *sock = SOCKET_I(inode);
100 const struct proto_ops *ops;
101 struct sock *sk = sock->sk;
102
103 ops = READ_ONCE(sock->ops);
104
105 /* PF_UNIX ? */
106 if (sk && ops && ops->family == PF_UNIX)
107 return unix_sk(sk);
108 }
109
110 return NULL;
111 }
112
unix_edge_successor(struct unix_edge * edge)113 static struct unix_vertex *unix_edge_successor(struct unix_edge *edge)
114 {
115 /* If an embryo socket has a fd,
116 * the listener indirectly holds the fd's refcnt.
117 */
118 if (edge->successor->listener)
119 return unix_sk(edge->successor->listener)->vertex;
120
121 return edge->successor->vertex;
122 }
123
124 static bool unix_graph_maybe_cyclic;
125 static bool unix_graph_grouped;
126
unix_update_graph(struct unix_vertex * vertex)127 static void unix_update_graph(struct unix_vertex *vertex)
128 {
129 /* If the receiver socket is not inflight, no cyclic
130 * reference could be formed.
131 */
132 if (!vertex)
133 return;
134
135 unix_graph_maybe_cyclic = true;
136 unix_graph_grouped = false;
137 }
138
139 static LIST_HEAD(unix_unvisited_vertices);
140
141 enum unix_vertex_index {
142 UNIX_VERTEX_INDEX_MARK1,
143 UNIX_VERTEX_INDEX_MARK2,
144 UNIX_VERTEX_INDEX_START,
145 };
146
147 static unsigned long unix_vertex_unvisited_index = UNIX_VERTEX_INDEX_MARK1;
148 static unsigned long unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START;
149
unix_add_edge(struct scm_fp_list * fpl,struct unix_edge * edge)150 static void unix_add_edge(struct scm_fp_list *fpl, struct unix_edge *edge)
151 {
152 struct unix_vertex *vertex = edge->predecessor->vertex;
153
154 if (!vertex) {
155 vertex = list_first_entry(&fpl->vertices, typeof(*vertex), entry);
156 vertex->index = unix_vertex_unvisited_index;
157 vertex->scc_index = ++unix_vertex_max_scc_index;
158 vertex->out_degree = 0;
159 INIT_LIST_HEAD(&vertex->edges);
160 INIT_LIST_HEAD(&vertex->scc_entry);
161
162 list_move_tail(&vertex->entry, &unix_unvisited_vertices);
163 edge->predecessor->vertex = vertex;
164 }
165
166 vertex->out_degree++;
167 list_add_tail(&edge->vertex_entry, &vertex->edges);
168
169 unix_update_graph(unix_edge_successor(edge));
170 }
171
unix_del_edge(struct scm_fp_list * fpl,struct unix_edge * edge)172 static void unix_del_edge(struct scm_fp_list *fpl, struct unix_edge *edge)
173 {
174 struct unix_vertex *vertex = edge->predecessor->vertex;
175
176 if (!fpl->dead)
177 unix_update_graph(unix_edge_successor(edge));
178
179 list_del(&edge->vertex_entry);
180 vertex->out_degree--;
181
182 if (!vertex->out_degree) {
183 edge->predecessor->vertex = NULL;
184 list_move_tail(&vertex->entry, &fpl->vertices);
185 }
186 }
187
unix_free_vertices(struct scm_fp_list * fpl)188 static void unix_free_vertices(struct scm_fp_list *fpl)
189 {
190 struct unix_vertex *vertex, *next_vertex;
191
192 list_for_each_entry_safe(vertex, next_vertex, &fpl->vertices, entry) {
193 list_del(&vertex->entry);
194 kfree(vertex);
195 }
196 }
197
198 static DEFINE_SPINLOCK(unix_gc_lock);
199 unsigned int unix_tot_inflight;
200
unix_add_edges(struct scm_fp_list * fpl,struct unix_sock * receiver)201 void unix_add_edges(struct scm_fp_list *fpl, struct unix_sock *receiver)
202 {
203 int i = 0, j = 0;
204
205 spin_lock(&unix_gc_lock);
206
207 if (!fpl->count_unix)
208 goto out;
209
210 do {
211 struct unix_sock *inflight = unix_get_socket(fpl->fp[j++]);
212 struct unix_edge *edge;
213
214 if (!inflight)
215 continue;
216
217 edge = fpl->edges + i++;
218 edge->predecessor = inflight;
219 edge->successor = receiver;
220
221 unix_add_edge(fpl, edge);
222 } while (i < fpl->count_unix);
223
224 receiver->scm_stat.nr_unix_fds += fpl->count_unix;
225 WRITE_ONCE(unix_tot_inflight, unix_tot_inflight + fpl->count_unix);
226 out:
227 WRITE_ONCE(fpl->user->unix_inflight, fpl->user->unix_inflight + fpl->count);
228
229 spin_unlock(&unix_gc_lock);
230
231 fpl->inflight = true;
232
233 unix_free_vertices(fpl);
234 }
235
unix_del_edges(struct scm_fp_list * fpl)236 void unix_del_edges(struct scm_fp_list *fpl)
237 {
238 struct unix_sock *receiver;
239 int i = 0;
240
241 spin_lock(&unix_gc_lock);
242
243 if (!fpl->count_unix)
244 goto out;
245
246 do {
247 struct unix_edge *edge = fpl->edges + i++;
248
249 unix_del_edge(fpl, edge);
250 } while (i < fpl->count_unix);
251
252 if (!fpl->dead) {
253 receiver = fpl->edges[0].successor;
254 receiver->scm_stat.nr_unix_fds -= fpl->count_unix;
255 }
256 WRITE_ONCE(unix_tot_inflight, unix_tot_inflight - fpl->count_unix);
257 out:
258 WRITE_ONCE(fpl->user->unix_inflight, fpl->user->unix_inflight - fpl->count);
259
260 spin_unlock(&unix_gc_lock);
261
262 fpl->inflight = false;
263 }
264
unix_update_edges(struct unix_sock * receiver)265 void unix_update_edges(struct unix_sock *receiver)
266 {
267 /* nr_unix_fds is only updated under unix_state_lock().
268 * If it's 0 here, the embryo socket is not part of the
269 * inflight graph, and GC will not see it, so no lock needed.
270 */
271 if (!receiver->scm_stat.nr_unix_fds) {
272 receiver->listener = NULL;
273 } else {
274 spin_lock(&unix_gc_lock);
275 unix_update_graph(unix_sk(receiver->listener)->vertex);
276 receiver->listener = NULL;
277 spin_unlock(&unix_gc_lock);
278 }
279 }
280
unix_prepare_fpl(struct scm_fp_list * fpl)281 int unix_prepare_fpl(struct scm_fp_list *fpl)
282 {
283 struct unix_vertex *vertex;
284 int i;
285
286 if (!fpl->count_unix)
287 return 0;
288
289 for (i = 0; i < fpl->count_unix; i++) {
290 vertex = kmalloc(sizeof(*vertex), GFP_KERNEL);
291 if (!vertex)
292 goto err;
293
294 list_add(&vertex->entry, &fpl->vertices);
295 }
296
297 fpl->edges = kvmalloc_array(fpl->count_unix, sizeof(*fpl->edges),
298 GFP_KERNEL_ACCOUNT);
299 if (!fpl->edges)
300 goto err;
301
302 return 0;
303
304 err:
305 unix_free_vertices(fpl);
306 return -ENOMEM;
307 }
308
unix_destroy_fpl(struct scm_fp_list * fpl)309 void unix_destroy_fpl(struct scm_fp_list *fpl)
310 {
311 if (fpl->inflight)
312 unix_del_edges(fpl);
313
314 kvfree(fpl->edges);
315 unix_free_vertices(fpl);
316 }
317
unix_vertex_dead(struct unix_vertex * vertex)318 static bool unix_vertex_dead(struct unix_vertex *vertex)
319 {
320 struct unix_edge *edge;
321 struct unix_sock *u;
322 long total_ref;
323
324 list_for_each_entry(edge, &vertex->edges, vertex_entry) {
325 struct unix_vertex *next_vertex = unix_edge_successor(edge);
326
327 /* The vertex's fd can be received by a non-inflight socket. */
328 if (!next_vertex)
329 return false;
330
331 /* The vertex's fd can be received by an inflight socket in
332 * another SCC.
333 */
334 if (next_vertex->scc_index != vertex->scc_index)
335 return false;
336 }
337
338 /* No receiver exists out of the same SCC. */
339
340 edge = list_first_entry(&vertex->edges, typeof(*edge), vertex_entry);
341 u = edge->predecessor;
342 total_ref = file_count(u->sk.sk_socket->file);
343
344 /* If not close()d, total_ref > out_degree. */
345 if (total_ref != vertex->out_degree)
346 return false;
347
348 return true;
349 }
350
unix_collect_skb(struct list_head * scc,struct sk_buff_head * hitlist)351 static void unix_collect_skb(struct list_head *scc, struct sk_buff_head *hitlist)
352 {
353 struct unix_vertex *vertex;
354
355 list_for_each_entry_reverse(vertex, scc, scc_entry) {
356 struct sk_buff_head *queue;
357 struct unix_edge *edge;
358 struct unix_sock *u;
359
360 edge = list_first_entry(&vertex->edges, typeof(*edge), vertex_entry);
361 u = edge->predecessor;
362 queue = &u->sk.sk_receive_queue;
363
364 spin_lock(&queue->lock);
365
366 if (u->sk.sk_state == TCP_LISTEN) {
367 struct sk_buff *skb;
368
369 skb_queue_walk(queue, skb) {
370 struct sk_buff_head *embryo_queue = &skb->sk->sk_receive_queue;
371
372 spin_lock(&embryo_queue->lock);
373 skb_queue_splice_init(embryo_queue, hitlist);
374 spin_unlock(&embryo_queue->lock);
375 }
376 } else {
377 skb_queue_splice_init(queue, hitlist);
378 }
379
380 spin_unlock(&queue->lock);
381 }
382 }
383
unix_scc_cyclic(struct list_head * scc)384 static bool unix_scc_cyclic(struct list_head *scc)
385 {
386 struct unix_vertex *vertex;
387 struct unix_edge *edge;
388
389 /* SCC containing multiple vertices ? */
390 if (!list_is_singular(scc))
391 return true;
392
393 vertex = list_first_entry(scc, typeof(*vertex), scc_entry);
394
395 /* Self-reference or a embryo-listener circle ? */
396 list_for_each_entry(edge, &vertex->edges, vertex_entry) {
397 if (unix_edge_successor(edge) == vertex)
398 return true;
399 }
400
401 return false;
402 }
403
404 static LIST_HEAD(unix_visited_vertices);
405 static unsigned long unix_vertex_grouped_index = UNIX_VERTEX_INDEX_MARK2;
406
__unix_walk_scc(struct unix_vertex * vertex,unsigned long * last_index,struct sk_buff_head * hitlist)407 static void __unix_walk_scc(struct unix_vertex *vertex, unsigned long *last_index,
408 struct sk_buff_head *hitlist)
409 {
410 LIST_HEAD(vertex_stack);
411 struct unix_edge *edge;
412 LIST_HEAD(edge_stack);
413
414 next_vertex:
415 /* Push vertex to vertex_stack and mark it as on-stack
416 * (index >= UNIX_VERTEX_INDEX_START).
417 * The vertex will be popped when finalising SCC later.
418 */
419 list_add(&vertex->scc_entry, &vertex_stack);
420
421 vertex->index = *last_index;
422 vertex->scc_index = *last_index;
423 (*last_index)++;
424
425 /* Explore neighbour vertices (receivers of the current vertex's fd). */
426 list_for_each_entry(edge, &vertex->edges, vertex_entry) {
427 struct unix_vertex *next_vertex = unix_edge_successor(edge);
428
429 if (!next_vertex)
430 continue;
431
432 if (next_vertex->index == unix_vertex_unvisited_index) {
433 /* Iterative deepening depth first search
434 *
435 * 1. Push a forward edge to edge_stack and set
436 * the successor to vertex for the next iteration.
437 */
438 list_add(&edge->stack_entry, &edge_stack);
439
440 vertex = next_vertex;
441 goto next_vertex;
442
443 /* 2. Pop the edge directed to the current vertex
444 * and restore the ancestor for backtracking.
445 */
446 prev_vertex:
447 edge = list_first_entry(&edge_stack, typeof(*edge), stack_entry);
448 list_del_init(&edge->stack_entry);
449
450 next_vertex = vertex;
451 vertex = edge->predecessor->vertex;
452
453 /* If the successor has a smaller scc_index, two vertices
454 * are in the same SCC, so propagate the smaller scc_index
455 * to skip SCC finalisation.
456 */
457 vertex->scc_index = min(vertex->scc_index, next_vertex->scc_index);
458 } else if (next_vertex->index != unix_vertex_grouped_index) {
459 /* Loop detected by a back/cross edge.
460 *
461 * The successor is on vertex_stack, so two vertices are in
462 * the same SCC. If the successor has a smaller *scc_index*,
463 * propagate it to skip SCC finalisation.
464 */
465 vertex->scc_index = min(vertex->scc_index, next_vertex->scc_index);
466 } else {
467 /* The successor was already grouped as another SCC */
468 }
469 }
470
471 if (vertex->index == vertex->scc_index) {
472 struct unix_vertex *v;
473 struct list_head scc;
474 bool scc_dead = true;
475
476 /* SCC finalised.
477 *
478 * If the scc_index was not updated, all the vertices above on
479 * vertex_stack are in the same SCC. Group them using scc_entry.
480 */
481 __list_cut_position(&scc, &vertex_stack, &vertex->scc_entry);
482
483 list_for_each_entry_reverse(v, &scc, scc_entry) {
484 /* Don't restart DFS from this vertex in unix_walk_scc(). */
485 list_move_tail(&v->entry, &unix_visited_vertices);
486
487 /* Mark vertex as off-stack. */
488 v->index = unix_vertex_grouped_index;
489
490 if (scc_dead)
491 scc_dead = unix_vertex_dead(v);
492 }
493
494 if (scc_dead) {
495 unix_collect_skb(&scc, hitlist);
496 } else {
497 if (unix_vertex_max_scc_index < vertex->scc_index)
498 unix_vertex_max_scc_index = vertex->scc_index;
499
500 if (!unix_graph_maybe_cyclic)
501 unix_graph_maybe_cyclic = unix_scc_cyclic(&scc);
502 }
503
504 list_del(&scc);
505 }
506
507 /* Need backtracking ? */
508 if (!list_empty(&edge_stack))
509 goto prev_vertex;
510 }
511
unix_walk_scc(struct sk_buff_head * hitlist)512 static void unix_walk_scc(struct sk_buff_head *hitlist)
513 {
514 unsigned long last_index = UNIX_VERTEX_INDEX_START;
515
516 unix_graph_maybe_cyclic = false;
517 unix_vertex_max_scc_index = UNIX_VERTEX_INDEX_START;
518
519 /* Visit every vertex exactly once.
520 * __unix_walk_scc() moves visited vertices to unix_visited_vertices.
521 */
522 while (!list_empty(&unix_unvisited_vertices)) {
523 struct unix_vertex *vertex;
524
525 vertex = list_first_entry(&unix_unvisited_vertices, typeof(*vertex), entry);
526 __unix_walk_scc(vertex, &last_index, hitlist);
527 }
528
529 list_replace_init(&unix_visited_vertices, &unix_unvisited_vertices);
530 swap(unix_vertex_unvisited_index, unix_vertex_grouped_index);
531
532 unix_graph_grouped = true;
533 }
534
unix_walk_scc_fast(struct sk_buff_head * hitlist)535 static void unix_walk_scc_fast(struct sk_buff_head *hitlist)
536 {
537 unix_graph_maybe_cyclic = false;
538
539 while (!list_empty(&unix_unvisited_vertices)) {
540 struct unix_vertex *vertex;
541 struct list_head scc;
542 bool scc_dead = true;
543
544 vertex = list_first_entry(&unix_unvisited_vertices, typeof(*vertex), entry);
545 list_add(&scc, &vertex->scc_entry);
546
547 list_for_each_entry_reverse(vertex, &scc, scc_entry) {
548 list_move_tail(&vertex->entry, &unix_visited_vertices);
549
550 if (scc_dead)
551 scc_dead = unix_vertex_dead(vertex);
552 }
553
554 if (scc_dead)
555 unix_collect_skb(&scc, hitlist);
556 else if (!unix_graph_maybe_cyclic)
557 unix_graph_maybe_cyclic = unix_scc_cyclic(&scc);
558
559 list_del(&scc);
560 }
561
562 list_replace_init(&unix_visited_vertices, &unix_unvisited_vertices);
563 }
564
565 static bool gc_in_progress;
566
__unix_gc(struct work_struct * work)567 static void __unix_gc(struct work_struct *work)
568 {
569 struct sk_buff_head hitlist;
570 struct sk_buff *skb;
571
572 spin_lock(&unix_gc_lock);
573
574 if (!unix_graph_maybe_cyclic) {
575 spin_unlock(&unix_gc_lock);
576 goto skip_gc;
577 }
578
579 __skb_queue_head_init(&hitlist);
580
581 if (unix_graph_grouped)
582 unix_walk_scc_fast(&hitlist);
583 else
584 unix_walk_scc(&hitlist);
585
586 spin_unlock(&unix_gc_lock);
587
588 skb_queue_walk(&hitlist, skb) {
589 if (UNIXCB(skb).fp)
590 UNIXCB(skb).fp->dead = true;
591 }
592
593 __skb_queue_purge_reason(&hitlist, SKB_DROP_REASON_SOCKET_CLOSE);
594 skip_gc:
595 WRITE_ONCE(gc_in_progress, false);
596 }
597
598 static DECLARE_WORK(unix_gc_work, __unix_gc);
599
unix_gc(void)600 void unix_gc(void)
601 {
602 WRITE_ONCE(gc_in_progress, true);
603 queue_work(system_dfl_wq, &unix_gc_work);
604 }
605
606 #define UNIX_INFLIGHT_TRIGGER_GC 16000
607 #define UNIX_INFLIGHT_SANE_USER (SCM_MAX_FD * 8)
608
wait_for_unix_gc(struct scm_fp_list * fpl)609 void wait_for_unix_gc(struct scm_fp_list *fpl)
610 {
611 /* If number of inflight sockets is insane,
612 * force a garbage collect right now.
613 *
614 * Paired with the WRITE_ONCE() in unix_inflight(),
615 * unix_notinflight(), and __unix_gc().
616 */
617 if (READ_ONCE(unix_tot_inflight) > UNIX_INFLIGHT_TRIGGER_GC &&
618 !READ_ONCE(gc_in_progress))
619 unix_gc();
620
621 /* Penalise users who want to send AF_UNIX sockets
622 * but whose sockets have not been received yet.
623 */
624 if (!fpl || !fpl->count_unix ||
625 READ_ONCE(fpl->user->unix_inflight) < UNIX_INFLIGHT_SANE_USER)
626 return;
627
628 if (READ_ONCE(gc_in_progress))
629 flush_work(&unix_gc_work);
630 }
631