xref: /linux/io_uring/zcrx.c (revision 91a4855d6c03e770e42f17c798a36a3c46e63de2)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/dma-map-ops.h>
5 #include <linux/mm.h>
6 #include <linux/nospec.h>
7 #include <linux/io_uring.h>
8 #include <linux/netdevice.h>
9 #include <linux/rtnetlink.h>
10 #include <linux/skbuff_ref.h>
11 #include <linux/anon_inodes.h>
12 
13 #include <net/page_pool/helpers.h>
14 #include <net/page_pool/memory_provider.h>
15 #include <net/netlink.h>
16 #include <net/netdev_queues.h>
17 #include <net/netdev_rx_queue.h>
18 #include <net/tcp.h>
19 #include <net/rps.h>
20 
21 #include <trace/events/page_pool.h>
22 
23 #include <uapi/linux/io_uring.h>
24 
25 #include "io_uring.h"
26 #include "kbuf.h"
27 #include "memmap.h"
28 #include "zcrx.h"
29 #include "rsrc.h"
30 
31 #define IO_ZCRX_AREA_SUPPORTED_FLAGS	(IORING_ZCRX_AREA_DMABUF)
32 
33 #define IO_DMA_ATTR (DMA_ATTR_SKIP_CPU_SYNC | DMA_ATTR_WEAK_ORDERING)
34 
35 static inline struct io_zcrx_ifq *io_pp_to_ifq(struct page_pool *pp)
36 {
37 	return pp->mp_priv;
38 }
39 
40 static inline struct io_zcrx_area *io_zcrx_iov_to_area(const struct net_iov *niov)
41 {
42 	struct net_iov_area *owner = net_iov_owner(niov);
43 
44 	return container_of(owner, struct io_zcrx_area, nia);
45 }
46 
47 static inline struct page *io_zcrx_iov_page(const struct net_iov *niov)
48 {
49 	struct io_zcrx_area *area = io_zcrx_iov_to_area(niov);
50 	unsigned niov_pages_shift;
51 
52 	lockdep_assert(!area->mem.is_dmabuf);
53 
54 	niov_pages_shift = area->ifq->niov_shift - PAGE_SHIFT;
55 	return area->mem.pages[net_iov_idx(niov) << niov_pages_shift];
56 }
57 
58 static int io_area_max_shift(struct io_zcrx_mem *mem)
59 {
60 	struct sg_table *sgt = mem->sgt;
61 	struct scatterlist *sg;
62 	unsigned shift = -1U;
63 	unsigned i;
64 
65 	for_each_sgtable_dma_sg(sgt, sg, i)
66 		shift = min(shift, __ffs(sg_dma_len(sg)));
67 	return shift;
68 }
69 
70 static int io_populate_area_dma(struct io_zcrx_ifq *ifq,
71 				struct io_zcrx_area *area)
72 {
73 	unsigned niov_size = 1U << ifq->niov_shift;
74 	struct sg_table *sgt = area->mem.sgt;
75 	struct scatterlist *sg;
76 	unsigned i, niov_idx = 0;
77 
78 	for_each_sgtable_dma_sg(sgt, sg, i) {
79 		dma_addr_t dma = sg_dma_address(sg);
80 		unsigned long sg_len = sg_dma_len(sg);
81 
82 		if (WARN_ON_ONCE(sg_len % niov_size))
83 			return -EINVAL;
84 
85 		while (sg_len && niov_idx < area->nia.num_niovs) {
86 			struct net_iov *niov = &area->nia.niovs[niov_idx];
87 
88 			if (net_mp_niov_set_dma_addr(niov, dma))
89 				return -EFAULT;
90 			sg_len -= niov_size;
91 			dma += niov_size;
92 			niov_idx++;
93 		}
94 	}
95 
96 	if (WARN_ON_ONCE(niov_idx != area->nia.num_niovs))
97 		return -EFAULT;
98 	return 0;
99 }
100 
101 static void io_release_dmabuf(struct io_zcrx_mem *mem)
102 {
103 	if (!IS_ENABLED(CONFIG_DMA_SHARED_BUFFER))
104 		return;
105 
106 	if (mem->sgt)
107 		dma_buf_unmap_attachment_unlocked(mem->attach, mem->sgt,
108 						  DMA_FROM_DEVICE);
109 	if (mem->attach)
110 		dma_buf_detach(mem->dmabuf, mem->attach);
111 	if (mem->dmabuf)
112 		dma_buf_put(mem->dmabuf);
113 
114 	mem->sgt = NULL;
115 	mem->attach = NULL;
116 	mem->dmabuf = NULL;
117 }
118 
119 static int io_import_dmabuf(struct io_zcrx_ifq *ifq,
120 			    struct io_zcrx_mem *mem,
121 			    struct io_uring_zcrx_area_reg *area_reg)
122 {
123 	unsigned long off = (unsigned long)area_reg->addr;
124 	unsigned long len = (unsigned long)area_reg->len;
125 	unsigned long total_size = 0;
126 	struct scatterlist *sg;
127 	int dmabuf_fd = area_reg->dmabuf_fd;
128 	int i, ret;
129 
130 	if (!ifq->dev)
131 		return -EINVAL;
132 	if (off)
133 		return -EINVAL;
134 	if (!IS_ENABLED(CONFIG_DMA_SHARED_BUFFER))
135 		return -EINVAL;
136 
137 	mem->is_dmabuf = true;
138 	mem->dmabuf = dma_buf_get(dmabuf_fd);
139 	if (IS_ERR(mem->dmabuf)) {
140 		ret = PTR_ERR(mem->dmabuf);
141 		mem->dmabuf = NULL;
142 		goto err;
143 	}
144 
145 	mem->attach = dma_buf_attach(mem->dmabuf, ifq->dev);
146 	if (IS_ERR(mem->attach)) {
147 		ret = PTR_ERR(mem->attach);
148 		mem->attach = NULL;
149 		goto err;
150 	}
151 
152 	mem->sgt = dma_buf_map_attachment_unlocked(mem->attach, DMA_FROM_DEVICE);
153 	if (IS_ERR(mem->sgt)) {
154 		ret = PTR_ERR(mem->sgt);
155 		mem->sgt = NULL;
156 		goto err;
157 	}
158 
159 	for_each_sgtable_dma_sg(mem->sgt, sg, i)
160 		total_size += sg_dma_len(sg);
161 
162 	if (total_size != len) {
163 		ret = -EINVAL;
164 		goto err;
165 	}
166 
167 	mem->size = len;
168 	return 0;
169 err:
170 	io_release_dmabuf(mem);
171 	return ret;
172 }
173 
174 static unsigned long io_count_account_pages(struct page **pages, unsigned nr_pages)
175 {
176 	struct folio *last_folio = NULL;
177 	unsigned long res = 0;
178 	int i;
179 
180 	for (i = 0; i < nr_pages; i++) {
181 		struct folio *folio = page_folio(pages[i]);
182 
183 		if (folio == last_folio)
184 			continue;
185 		last_folio = folio;
186 		res += folio_nr_pages(folio);
187 	}
188 	return res;
189 }
190 
191 static int io_import_umem(struct io_zcrx_ifq *ifq,
192 			  struct io_zcrx_mem *mem,
193 			  struct io_uring_zcrx_area_reg *area_reg)
194 {
195 	struct page **pages;
196 	int nr_pages, ret;
197 	bool mapped = false;
198 
199 	if (area_reg->dmabuf_fd)
200 		return -EINVAL;
201 	if (!area_reg->addr)
202 		return -EFAULT;
203 	pages = io_pin_pages((unsigned long)area_reg->addr, area_reg->len,
204 				   &nr_pages);
205 	if (IS_ERR(pages))
206 		return PTR_ERR(pages);
207 
208 	ret = sg_alloc_table_from_pages(&mem->page_sg_table, pages, nr_pages,
209 					0, (unsigned long)nr_pages << PAGE_SHIFT,
210 					GFP_KERNEL_ACCOUNT);
211 	if (ret)
212 		goto out_err;
213 
214 	if (ifq->dev) {
215 		ret = dma_map_sgtable(ifq->dev, &mem->page_sg_table,
216 				      DMA_FROM_DEVICE, IO_DMA_ATTR);
217 		if (ret < 0)
218 			goto out_err;
219 		mapped = true;
220 	}
221 
222 	mem->account_pages = io_count_account_pages(pages, nr_pages);
223 	ret = io_account_mem(ifq->user, ifq->mm_account, mem->account_pages);
224 	if (ret < 0) {
225 		mem->account_pages = 0;
226 		goto out_err;
227 	}
228 
229 	mem->sgt = &mem->page_sg_table;
230 	mem->pages = pages;
231 	mem->nr_folios = nr_pages;
232 	mem->size = area_reg->len;
233 	return ret;
234 out_err:
235 	if (mapped)
236 		dma_unmap_sgtable(ifq->dev, &mem->page_sg_table,
237 				  DMA_FROM_DEVICE, IO_DMA_ATTR);
238 	sg_free_table(&mem->page_sg_table);
239 	unpin_user_pages(pages, nr_pages);
240 	kvfree(pages);
241 	return ret;
242 }
243 
244 static void io_release_area_mem(struct io_zcrx_mem *mem)
245 {
246 	if (mem->is_dmabuf) {
247 		io_release_dmabuf(mem);
248 		return;
249 	}
250 	if (mem->pages) {
251 		unpin_user_pages(mem->pages, mem->nr_folios);
252 		sg_free_table(mem->sgt);
253 		mem->sgt = NULL;
254 		kvfree(mem->pages);
255 	}
256 }
257 
258 static int io_import_area(struct io_zcrx_ifq *ifq,
259 			  struct io_zcrx_mem *mem,
260 			  struct io_uring_zcrx_area_reg *area_reg)
261 {
262 	int ret;
263 
264 	if (area_reg->flags & ~IO_ZCRX_AREA_SUPPORTED_FLAGS)
265 		return -EINVAL;
266 	if (area_reg->rq_area_token)
267 		return -EINVAL;
268 	if (area_reg->__resv2[0] || area_reg->__resv2[1])
269 		return -EINVAL;
270 
271 	ret = io_validate_user_buf_range(area_reg->addr, area_reg->len);
272 	if (ret)
273 		return ret;
274 	if (area_reg->addr & ~PAGE_MASK || area_reg->len & ~PAGE_MASK)
275 		return -EINVAL;
276 
277 	if (area_reg->flags & IORING_ZCRX_AREA_DMABUF)
278 		return io_import_dmabuf(ifq, mem, area_reg);
279 	return io_import_umem(ifq, mem, area_reg);
280 }
281 
282 static void io_zcrx_unmap_area(struct io_zcrx_ifq *ifq,
283 				struct io_zcrx_area *area)
284 {
285 	int i;
286 
287 	guard(mutex)(&ifq->pp_lock);
288 	if (!area->is_mapped)
289 		return;
290 	area->is_mapped = false;
291 
292 	if (area->nia.niovs) {
293 		for (i = 0; i < area->nia.num_niovs; i++)
294 			net_mp_niov_set_dma_addr(&area->nia.niovs[i], 0);
295 	}
296 
297 	if (area->mem.is_dmabuf) {
298 		io_release_dmabuf(&area->mem);
299 	} else {
300 		dma_unmap_sgtable(ifq->dev, &area->mem.page_sg_table,
301 				  DMA_FROM_DEVICE, IO_DMA_ATTR);
302 	}
303 }
304 
305 static void zcrx_sync_for_device(struct page_pool *pp, struct io_zcrx_ifq *zcrx,
306 				 netmem_ref *netmems, unsigned nr)
307 {
308 #if defined(CONFIG_HAS_DMA) && defined(CONFIG_DMA_NEED_SYNC)
309 	struct device *dev = pp->p.dev;
310 	unsigned i, niov_size;
311 	dma_addr_t dma_addr;
312 
313 	if (!dma_dev_need_sync(dev))
314 		return;
315 	niov_size = 1U << zcrx->niov_shift;
316 
317 	for (i = 0; i < nr; i++) {
318 		dma_addr = page_pool_get_dma_addr_netmem(netmems[i]);
319 		__dma_sync_single_for_device(dev, dma_addr + pp->p.offset,
320 					     niov_size, pp->p.dma_dir);
321 	}
322 #endif
323 }
324 
325 #define IO_RQ_MAX_ENTRIES		32768
326 
327 #define IO_SKBS_PER_CALL_LIMIT	20
328 
329 struct io_zcrx_args {
330 	struct io_kiocb		*req;
331 	struct io_zcrx_ifq	*ifq;
332 	struct socket		*sock;
333 	unsigned		nr_skbs;
334 };
335 
336 static const struct memory_provider_ops io_uring_pp_zc_ops;
337 
338 static inline atomic_t *io_get_user_counter(struct net_iov *niov)
339 {
340 	struct io_zcrx_area *area = io_zcrx_iov_to_area(niov);
341 
342 	return &area->user_refs[net_iov_idx(niov)];
343 }
344 
345 static bool io_zcrx_put_niov_uref(struct net_iov *niov)
346 {
347 	atomic_t *uref = io_get_user_counter(niov);
348 	int old;
349 
350 	old = atomic_read(uref);
351 	do {
352 		if (unlikely(old == 0))
353 			return false;
354 	} while (!atomic_try_cmpxchg(uref, &old, old - 1));
355 
356 	return true;
357 }
358 
359 static void io_zcrx_get_niov_uref(struct net_iov *niov)
360 {
361 	atomic_inc(io_get_user_counter(niov));
362 }
363 
364 static void io_fill_zcrx_offsets(struct io_uring_zcrx_offsets *offsets)
365 {
366 	offsets->head = offsetof(struct io_uring, head);
367 	offsets->tail = offsetof(struct io_uring, tail);
368 	offsets->rqes = ALIGN(sizeof(struct io_uring), L1_CACHE_BYTES);
369 }
370 
371 static int io_allocate_rbuf_ring(struct io_ring_ctx *ctx,
372 				 struct io_zcrx_ifq *ifq,
373 				 struct io_uring_zcrx_ifq_reg *reg,
374 				 struct io_uring_region_desc *rd,
375 				 u32 id)
376 {
377 	u64 mmap_offset;
378 	size_t off, size;
379 	void *ptr;
380 	int ret;
381 
382 	io_fill_zcrx_offsets(&reg->offsets);
383 	off = reg->offsets.rqes;
384 	size = off + sizeof(struct io_uring_zcrx_rqe) * reg->rq_entries;
385 	if (size > rd->size)
386 		return -EINVAL;
387 
388 	mmap_offset = IORING_MAP_OFF_ZCRX_REGION;
389 	mmap_offset += (u64)id << IORING_OFF_ZCRX_SHIFT;
390 
391 	ret = io_create_region(ctx, &ifq->rq_region, rd, mmap_offset);
392 	if (ret < 0)
393 		return ret;
394 
395 	ptr = io_region_get_ptr(&ifq->rq_region);
396 	ifq->rq.ring = (struct io_uring *)ptr;
397 	ifq->rq.rqes = (struct io_uring_zcrx_rqe *)(ptr + off);
398 
399 	return 0;
400 }
401 
402 static void io_free_rbuf_ring(struct io_zcrx_ifq *ifq)
403 {
404 	io_free_region(ifq->user, &ifq->rq_region);
405 	ifq->rq.ring = NULL;
406 	ifq->rq.rqes = NULL;
407 }
408 
409 static void io_zcrx_free_area(struct io_zcrx_ifq *ifq,
410 			      struct io_zcrx_area *area)
411 {
412 	io_zcrx_unmap_area(ifq, area);
413 	io_release_area_mem(&area->mem);
414 
415 	if (area->mem.account_pages)
416 		io_unaccount_mem(ifq->user, ifq->mm_account,
417 				 area->mem.account_pages);
418 
419 	kvfree(area->freelist);
420 	kvfree(area->nia.niovs);
421 	kvfree(area->user_refs);
422 	kfree(area);
423 }
424 
425 static int io_zcrx_append_area(struct io_zcrx_ifq *ifq,
426 				struct io_zcrx_area *area)
427 {
428 	bool kern_readable = !area->mem.is_dmabuf;
429 
430 	if (WARN_ON_ONCE(ifq->area))
431 		return -EINVAL;
432 	if (WARN_ON_ONCE(ifq->kern_readable != kern_readable))
433 		return -EINVAL;
434 
435 	ifq->area = area;
436 	return 0;
437 }
438 
439 static int io_zcrx_create_area(struct io_zcrx_ifq *ifq,
440 			       struct io_uring_zcrx_area_reg *area_reg,
441 			       struct io_uring_zcrx_ifq_reg *reg)
442 {
443 	int buf_size_shift = PAGE_SHIFT;
444 	struct io_zcrx_area *area;
445 	unsigned nr_iovs;
446 	int i, ret;
447 
448 	if (reg->rx_buf_len) {
449 		if (!is_power_of_2(reg->rx_buf_len) ||
450 		     reg->rx_buf_len < PAGE_SIZE)
451 			return -EINVAL;
452 		buf_size_shift = ilog2(reg->rx_buf_len);
453 	}
454 	if (!ifq->dev && buf_size_shift != PAGE_SHIFT)
455 		return -EOPNOTSUPP;
456 
457 	ret = -ENOMEM;
458 	area = kzalloc_obj(*area);
459 	if (!area)
460 		goto err;
461 	area->ifq = ifq;
462 
463 	ret = io_import_area(ifq, &area->mem, area_reg);
464 	if (ret)
465 		goto err;
466 	if (ifq->dev)
467 		area->is_mapped = true;
468 
469 	if (ifq->dev && buf_size_shift > io_area_max_shift(&area->mem)) {
470 		ret = -ERANGE;
471 		goto err;
472 	}
473 
474 	ifq->niov_shift = buf_size_shift;
475 	nr_iovs = area->mem.size >> ifq->niov_shift;
476 	area->nia.num_niovs = nr_iovs;
477 
478 	ret = -ENOMEM;
479 	area->nia.niovs = kvmalloc_objs(area->nia.niovs[0], nr_iovs,
480 					GFP_KERNEL_ACCOUNT | __GFP_ZERO);
481 	if (!area->nia.niovs)
482 		goto err;
483 
484 	area->freelist = kvmalloc_array(nr_iovs, sizeof(area->freelist[0]),
485 					GFP_KERNEL_ACCOUNT | __GFP_ZERO);
486 	if (!area->freelist)
487 		goto err;
488 
489 	area->user_refs = kvmalloc_objs(area->user_refs[0], nr_iovs,
490 					GFP_KERNEL_ACCOUNT | __GFP_ZERO);
491 	if (!area->user_refs)
492 		goto err;
493 
494 	for (i = 0; i < nr_iovs; i++) {
495 		struct net_iov *niov = &area->nia.niovs[i];
496 
497 		niov->owner = &area->nia;
498 		area->freelist[i] = i;
499 		atomic_set(&area->user_refs[i], 0);
500 		niov->type = NET_IOV_IOURING;
501 	}
502 
503 	if (ifq->dev) {
504 		ret = io_populate_area_dma(ifq, area);
505 		if (ret)
506 			goto err;
507 	}
508 
509 	area->free_count = nr_iovs;
510 	/* we're only supporting one area per ifq for now */
511 	area->area_id = 0;
512 	area_reg->rq_area_token = (u64)area->area_id << IORING_ZCRX_AREA_SHIFT;
513 	spin_lock_init(&area->freelist_lock);
514 
515 	ret = io_zcrx_append_area(ifq, area);
516 	if (!ret)
517 		return 0;
518 err:
519 	if (area)
520 		io_zcrx_free_area(ifq, area);
521 	return ret;
522 }
523 
524 static struct io_zcrx_ifq *io_zcrx_ifq_alloc(struct io_ring_ctx *ctx)
525 {
526 	struct io_zcrx_ifq *ifq;
527 
528 	ifq = kzalloc_obj(*ifq);
529 	if (!ifq)
530 		return NULL;
531 
532 	ifq->if_rxq = -1;
533 	spin_lock_init(&ifq->rq.lock);
534 	mutex_init(&ifq->pp_lock);
535 	refcount_set(&ifq->refs, 1);
536 	refcount_set(&ifq->user_refs, 1);
537 	return ifq;
538 }
539 
540 static void io_zcrx_drop_netdev(struct io_zcrx_ifq *ifq)
541 {
542 	guard(mutex)(&ifq->pp_lock);
543 
544 	if (!ifq->netdev)
545 		return;
546 	netdev_put(ifq->netdev, &ifq->netdev_tracker);
547 	ifq->netdev = NULL;
548 }
549 
550 static void io_close_queue(struct io_zcrx_ifq *ifq)
551 {
552 	struct net_device *netdev;
553 	netdevice_tracker netdev_tracker;
554 	struct pp_memory_provider_params p = {
555 		.mp_ops = &io_uring_pp_zc_ops,
556 		.mp_priv = ifq,
557 	};
558 
559 	scoped_guard(mutex, &ifq->pp_lock) {
560 		netdev = ifq->netdev;
561 		netdev_tracker = ifq->netdev_tracker;
562 		ifq->netdev = NULL;
563 	}
564 
565 	if (netdev) {
566 		if (ifq->if_rxq != -1) {
567 			netdev_lock(netdev);
568 			netif_mp_close_rxq(netdev, ifq->if_rxq, &p);
569 			netdev_unlock(netdev);
570 		}
571 		netdev_put(netdev, &netdev_tracker);
572 	}
573 	ifq->if_rxq = -1;
574 }
575 
576 static void io_zcrx_ifq_free(struct io_zcrx_ifq *ifq)
577 {
578 	io_close_queue(ifq);
579 
580 	if (ifq->area)
581 		io_zcrx_free_area(ifq, ifq->area);
582 	free_uid(ifq->user);
583 	if (ifq->mm_account)
584 		mmdrop(ifq->mm_account);
585 	if (ifq->dev)
586 		put_device(ifq->dev);
587 
588 	io_free_rbuf_ring(ifq);
589 	mutex_destroy(&ifq->pp_lock);
590 	kfree(ifq);
591 }
592 
593 static void io_put_zcrx_ifq(struct io_zcrx_ifq *ifq)
594 {
595 	if (refcount_dec_and_test(&ifq->refs))
596 		io_zcrx_ifq_free(ifq);
597 }
598 
599 static void io_zcrx_return_niov_freelist(struct net_iov *niov)
600 {
601 	struct io_zcrx_area *area = io_zcrx_iov_to_area(niov);
602 
603 	guard(spinlock_bh)(&area->freelist_lock);
604 	area->freelist[area->free_count++] = net_iov_idx(niov);
605 }
606 
607 static struct net_iov *zcrx_get_free_niov(struct io_zcrx_area *area)
608 {
609 	unsigned niov_idx;
610 
611 	lockdep_assert_held(&area->freelist_lock);
612 
613 	if (unlikely(!area->free_count))
614 		return NULL;
615 
616 	niov_idx = area->freelist[--area->free_count];
617 	return &area->nia.niovs[niov_idx];
618 }
619 
620 static void io_zcrx_return_niov(struct net_iov *niov)
621 {
622 	netmem_ref netmem = net_iov_to_netmem(niov);
623 
624 	if (!niov->desc.pp) {
625 		/* copy fallback allocated niovs */
626 		io_zcrx_return_niov_freelist(niov);
627 		return;
628 	}
629 	page_pool_put_unrefed_netmem(niov->desc.pp, netmem, -1, false);
630 }
631 
632 static void io_zcrx_scrub(struct io_zcrx_ifq *ifq)
633 {
634 	struct io_zcrx_area *area = ifq->area;
635 	int i;
636 
637 	if (!area)
638 		return;
639 
640 	/* Reclaim back all buffers given to the user space. */
641 	for (i = 0; i < area->nia.num_niovs; i++) {
642 		struct net_iov *niov = &area->nia.niovs[i];
643 		int nr;
644 
645 		if (!atomic_read(io_get_user_counter(niov)))
646 			continue;
647 		nr = atomic_xchg(io_get_user_counter(niov), 0);
648 		if (nr && !page_pool_unref_netmem(net_iov_to_netmem(niov), nr))
649 			io_zcrx_return_niov(niov);
650 	}
651 }
652 
653 static void zcrx_unregister_user(struct io_zcrx_ifq *ifq)
654 {
655 	if (refcount_dec_and_test(&ifq->user_refs)) {
656 		io_close_queue(ifq);
657 		io_zcrx_scrub(ifq);
658 	}
659 }
660 
661 static void zcrx_unregister(struct io_zcrx_ifq *ifq)
662 {
663 	zcrx_unregister_user(ifq);
664 	io_put_zcrx_ifq(ifq);
665 }
666 
667 struct io_mapped_region *io_zcrx_get_region(struct io_ring_ctx *ctx,
668 					    unsigned int id)
669 {
670 	struct io_zcrx_ifq *ifq = xa_load(&ctx->zcrx_ctxs, id);
671 
672 	lockdep_assert_held(&ctx->mmap_lock);
673 
674 	return ifq ? &ifq->rq_region : NULL;
675 }
676 
677 static int zcrx_box_release(struct inode *inode, struct file *file)
678 {
679 	struct io_zcrx_ifq *ifq = file->private_data;
680 
681 	if (WARN_ON_ONCE(!ifq))
682 		return -EFAULT;
683 	zcrx_unregister(ifq);
684 	return 0;
685 }
686 
687 static const struct file_operations zcrx_box_fops = {
688 	.owner		= THIS_MODULE,
689 	.release	= zcrx_box_release,
690 };
691 
692 static int zcrx_export(struct io_ring_ctx *ctx, struct io_zcrx_ifq *ifq,
693 		       struct zcrx_ctrl *ctrl, void __user *arg)
694 {
695 	struct zcrx_ctrl_export *ce = &ctrl->zc_export;
696 	struct file *file;
697 	int fd = -1;
698 
699 	if (!mem_is_zero(ce, sizeof(*ce)))
700 		return -EINVAL;
701 	fd = get_unused_fd_flags(O_CLOEXEC);
702 	if (fd < 0)
703 		return fd;
704 
705 	ce->zcrx_fd = fd;
706 	if (copy_to_user(arg, ctrl, sizeof(*ctrl))) {
707 		put_unused_fd(fd);
708 		return -EFAULT;
709 	}
710 
711 	refcount_inc(&ifq->refs);
712 	refcount_inc(&ifq->user_refs);
713 
714 	file = anon_inode_create_getfile("[zcrx]", &zcrx_box_fops,
715 					 ifq, O_CLOEXEC, NULL);
716 	if (IS_ERR(file)) {
717 		put_unused_fd(fd);
718 		zcrx_unregister(ifq);
719 		return PTR_ERR(file);
720 	}
721 
722 	fd_install(fd, file);
723 	return 0;
724 }
725 
726 static int import_zcrx(struct io_ring_ctx *ctx,
727 		       struct io_uring_zcrx_ifq_reg __user *arg,
728 		       struct io_uring_zcrx_ifq_reg *reg)
729 {
730 	struct io_zcrx_ifq *ifq;
731 	struct file *file;
732 	int fd, ret;
733 	u32 id;
734 
735 	if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
736 		return -EINVAL;
737 	if (!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)))
738 		return -EINVAL;
739 	if (reg->if_rxq || reg->rq_entries || reg->area_ptr || reg->region_ptr)
740 		return -EINVAL;
741 	if (reg->flags & ~ZCRX_REG_IMPORT)
742 		return -EINVAL;
743 
744 	fd = reg->if_idx;
745 	CLASS(fd, f)(fd);
746 	if (fd_empty(f))
747 		return -EBADF;
748 
749 	file = fd_file(f);
750 	if (file->f_op != &zcrx_box_fops || !file->private_data)
751 		return -EBADF;
752 
753 	ifq = file->private_data;
754 	refcount_inc(&ifq->refs);
755 	refcount_inc(&ifq->user_refs);
756 
757 	scoped_guard(mutex, &ctx->mmap_lock) {
758 		ret = xa_alloc(&ctx->zcrx_ctxs, &id, NULL, xa_limit_31b, GFP_KERNEL);
759 		if (ret)
760 			goto err;
761 	}
762 
763 	reg->zcrx_id = id;
764 	io_fill_zcrx_offsets(&reg->offsets);
765 	if (copy_to_user(arg, reg, sizeof(*reg))) {
766 		ret = -EFAULT;
767 		goto err_xa_erase;
768 	}
769 
770 	scoped_guard(mutex, &ctx->mmap_lock) {
771 		ret = -ENOMEM;
772 		if (xa_store(&ctx->zcrx_ctxs, id, ifq, GFP_KERNEL))
773 			goto err_xa_erase;
774 	}
775 
776 	return 0;
777 err_xa_erase:
778 	scoped_guard(mutex, &ctx->mmap_lock)
779 		xa_erase(&ctx->zcrx_ctxs, id);
780 err:
781 	zcrx_unregister(ifq);
782 	return ret;
783 }
784 
785 static int zcrx_register_netdev(struct io_zcrx_ifq *ifq,
786 				struct io_uring_zcrx_ifq_reg *reg,
787 				struct io_uring_zcrx_area_reg *area)
788 {
789 	struct pp_memory_provider_params mp_param = {};
790 	unsigned if_rxq = reg->if_rxq;
791 	int ret;
792 
793 	ifq->netdev = netdev_get_by_index_lock(current->nsproxy->net_ns,
794 						reg->if_idx);
795 	if (!ifq->netdev)
796 		return -ENODEV;
797 
798 	netdev_hold(ifq->netdev, &ifq->netdev_tracker, GFP_KERNEL);
799 
800 	ifq->dev = netdev_queue_get_dma_dev(ifq->netdev, if_rxq, NETDEV_QUEUE_TYPE_RX);
801 	if (!ifq->dev) {
802 		ret = -EOPNOTSUPP;
803 		goto netdev_put_unlock;
804 	}
805 	get_device(ifq->dev);
806 
807 	ret = io_zcrx_create_area(ifq, area, reg);
808 	if (ret)
809 		goto netdev_put_unlock;
810 
811 	if (reg->rx_buf_len)
812 		mp_param.rx_page_size = 1U << ifq->niov_shift;
813 	mp_param.mp_ops = &io_uring_pp_zc_ops;
814 	mp_param.mp_priv = ifq;
815 	ret = netif_mp_open_rxq(ifq->netdev, if_rxq, &mp_param, NULL);
816 	if (ret)
817 		goto netdev_put_unlock;
818 
819 	ifq->if_rxq = if_rxq;
820 	ret = 0;
821 netdev_put_unlock:
822 	netdev_unlock(ifq->netdev);
823 	return ret;
824 }
825 
826 int io_register_zcrx(struct io_ring_ctx *ctx,
827 		     struct io_uring_zcrx_ifq_reg __user *arg)
828 {
829 	struct io_uring_zcrx_area_reg area;
830 	struct io_uring_zcrx_ifq_reg reg;
831 	struct io_uring_region_desc rd;
832 	struct io_zcrx_ifq *ifq;
833 	int ret;
834 	u32 id;
835 
836 	/*
837 	 * 1. Interface queue allocation.
838 	 * 2. It can observe data destined for sockets of other tasks.
839 	 */
840 	if (!capable(CAP_NET_ADMIN))
841 		return -EPERM;
842 
843 	/* mandatory io_uring features for zc rx */
844 	if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
845 		return -EINVAL;
846 	if (!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)))
847 		return -EINVAL;
848 	if (copy_from_user(&reg, arg, sizeof(reg)))
849 		return -EFAULT;
850 	if (!mem_is_zero(&reg.__resv, sizeof(reg.__resv)) || reg.zcrx_id)
851 		return -EINVAL;
852 	if (reg.flags & ~ZCRX_SUPPORTED_REG_FLAGS)
853 		return -EINVAL;
854 	if (reg.flags & ZCRX_REG_IMPORT)
855 		return import_zcrx(ctx, arg, &reg);
856 	if (copy_from_user(&rd, u64_to_user_ptr(reg.region_ptr), sizeof(rd)))
857 		return -EFAULT;
858 	if (reg.if_rxq == -1 || !reg.rq_entries)
859 		return -EINVAL;
860 	if ((reg.if_rxq || reg.if_idx) && (reg.flags & ZCRX_REG_NODEV))
861 		return -EINVAL;
862 	if (reg.rq_entries > IO_RQ_MAX_ENTRIES) {
863 		if (!(ctx->flags & IORING_SETUP_CLAMP))
864 			return -EINVAL;
865 		reg.rq_entries = IO_RQ_MAX_ENTRIES;
866 	}
867 	reg.rq_entries = roundup_pow_of_two(reg.rq_entries);
868 
869 	if (copy_from_user(&area, u64_to_user_ptr(reg.area_ptr), sizeof(area)))
870 		return -EFAULT;
871 
872 	ifq = io_zcrx_ifq_alloc(ctx);
873 	if (!ifq)
874 		return -ENOMEM;
875 
876 	if (ctx->user) {
877 		get_uid(ctx->user);
878 		ifq->user = ctx->user;
879 	}
880 	if (ctx->mm_account) {
881 		mmgrab(ctx->mm_account);
882 		ifq->mm_account = ctx->mm_account;
883 	}
884 	ifq->rq.nr_entries = reg.rq_entries;
885 
886 	scoped_guard(mutex, &ctx->mmap_lock) {
887 		/* preallocate id */
888 		ret = xa_alloc(&ctx->zcrx_ctxs, &id, NULL, xa_limit_31b, GFP_KERNEL);
889 		if (ret)
890 			goto ifq_free;
891 	}
892 
893 	ret = io_allocate_rbuf_ring(ctx, ifq, &reg, &rd, id);
894 	if (ret)
895 		goto err;
896 
897 	ifq->kern_readable = !(area.flags & IORING_ZCRX_AREA_DMABUF);
898 
899 	if (!(reg.flags & ZCRX_REG_NODEV)) {
900 		ret = zcrx_register_netdev(ifq, &reg, &area);
901 		if (ret)
902 			goto err;
903 	} else {
904 		ret = io_zcrx_create_area(ifq, &area, &reg);
905 		if (ret)
906 			goto err;
907 	}
908 
909 	reg.zcrx_id = id;
910 
911 	scoped_guard(mutex, &ctx->mmap_lock) {
912 		/* publish ifq */
913 		ret = -ENOMEM;
914 		if (xa_store(&ctx->zcrx_ctxs, id, ifq, GFP_KERNEL))
915 			goto err;
916 	}
917 
918 	reg.rx_buf_len = 1U << ifq->niov_shift;
919 
920 	if (copy_to_user(arg, &reg, sizeof(reg)) ||
921 	    copy_to_user(u64_to_user_ptr(reg.region_ptr), &rd, sizeof(rd)) ||
922 	    copy_to_user(u64_to_user_ptr(reg.area_ptr), &area, sizeof(area))) {
923 		ret = -EFAULT;
924 		goto err;
925 	}
926 	return 0;
927 err:
928 	scoped_guard(mutex, &ctx->mmap_lock)
929 		xa_erase(&ctx->zcrx_ctxs, id);
930 ifq_free:
931 	zcrx_unregister(ifq);
932 	return ret;
933 }
934 
935 static inline bool is_zcrx_entry_marked(struct io_ring_ctx *ctx, unsigned long id)
936 {
937 	return xa_get_mark(&ctx->zcrx_ctxs, id, XA_MARK_1);
938 }
939 
940 static inline void set_zcrx_entry_mark(struct io_ring_ctx *ctx, unsigned long id)
941 {
942 	xa_set_mark(&ctx->zcrx_ctxs, id, XA_MARK_1);
943 }
944 
945 void io_terminate_zcrx(struct io_ring_ctx *ctx)
946 {
947 	struct io_zcrx_ifq *ifq;
948 	unsigned long id = 0;
949 
950 	lockdep_assert_held(&ctx->uring_lock);
951 
952 	while (1) {
953 		scoped_guard(mutex, &ctx->mmap_lock)
954 			ifq = xa_find(&ctx->zcrx_ctxs, &id, ULONG_MAX, XA_PRESENT);
955 		if (!ifq)
956 			break;
957 		if (WARN_ON_ONCE(is_zcrx_entry_marked(ctx, id)))
958 			break;
959 		set_zcrx_entry_mark(ctx, id);
960 		id++;
961 		zcrx_unregister_user(ifq);
962 	}
963 }
964 
965 void io_unregister_zcrx(struct io_ring_ctx *ctx)
966 {
967 	struct io_zcrx_ifq *ifq;
968 
969 	lockdep_assert_held(&ctx->uring_lock);
970 
971 	while (1) {
972 		scoped_guard(mutex, &ctx->mmap_lock) {
973 			unsigned long id = 0;
974 
975 			ifq = xa_find(&ctx->zcrx_ctxs, &id, ULONG_MAX, XA_PRESENT);
976 			if (ifq) {
977 				if (WARN_ON_ONCE(!is_zcrx_entry_marked(ctx, id))) {
978 					ifq = NULL;
979 					break;
980 				}
981 				xa_erase(&ctx->zcrx_ctxs, id);
982 			}
983 		}
984 		if (!ifq)
985 			break;
986 		io_put_zcrx_ifq(ifq);
987 	}
988 
989 	xa_destroy(&ctx->zcrx_ctxs);
990 }
991 
992 static inline u32 zcrx_rq_entries(struct zcrx_rq *rq)
993 {
994 	u32 entries;
995 
996 	entries = smp_load_acquire(&rq->ring->tail) - rq->cached_head;
997 	return min(entries, rq->nr_entries);
998 }
999 
1000 static struct io_uring_zcrx_rqe *zcrx_next_rqe(struct zcrx_rq *rq, unsigned mask)
1001 {
1002 	unsigned int idx = rq->cached_head++ & mask;
1003 
1004 	return &rq->rqes[idx];
1005 }
1006 
1007 static inline bool io_parse_rqe(struct io_uring_zcrx_rqe *rqe,
1008 				struct io_zcrx_ifq *ifq,
1009 				struct net_iov **ret_niov)
1010 {
1011 	__u64 off = READ_ONCE(rqe->off);
1012 	unsigned niov_idx, area_idx;
1013 	struct io_zcrx_area *area;
1014 
1015 	area_idx = off >> IORING_ZCRX_AREA_SHIFT;
1016 	niov_idx = (off & ~IORING_ZCRX_AREA_MASK) >> ifq->niov_shift;
1017 
1018 	if (unlikely(rqe->__pad || area_idx))
1019 		return false;
1020 	area = ifq->area;
1021 
1022 	if (unlikely(niov_idx >= area->nia.num_niovs))
1023 		return false;
1024 	niov_idx = array_index_nospec(niov_idx, area->nia.num_niovs);
1025 
1026 	*ret_niov = &area->nia.niovs[niov_idx];
1027 	return true;
1028 }
1029 
1030 static unsigned io_zcrx_ring_refill(struct page_pool *pp,
1031 				    struct io_zcrx_ifq *ifq,
1032 				    netmem_ref *netmems, unsigned to_alloc)
1033 {
1034 	struct zcrx_rq *rq = &ifq->rq;
1035 	unsigned int mask = rq->nr_entries - 1;
1036 	unsigned int entries;
1037 	unsigned allocated = 0;
1038 
1039 	guard(spinlock_bh)(&rq->lock);
1040 
1041 	entries = zcrx_rq_entries(rq);
1042 	entries = min_t(unsigned, entries, to_alloc);
1043 	if (unlikely(!entries))
1044 		return 0;
1045 
1046 	do {
1047 		struct io_uring_zcrx_rqe *rqe = zcrx_next_rqe(rq, mask);
1048 		struct net_iov *niov;
1049 		netmem_ref netmem;
1050 
1051 		if (!io_parse_rqe(rqe, ifq, &niov))
1052 			continue;
1053 		if (!io_zcrx_put_niov_uref(niov))
1054 			continue;
1055 
1056 		netmem = net_iov_to_netmem(niov);
1057 		if (!page_pool_unref_and_test(netmem))
1058 			continue;
1059 
1060 		if (unlikely(niov->desc.pp != pp)) {
1061 			io_zcrx_return_niov(niov);
1062 			continue;
1063 		}
1064 
1065 		netmems[allocated] = netmem;
1066 		allocated++;
1067 	} while (--entries);
1068 
1069 	smp_store_release(&rq->ring->head, rq->cached_head);
1070 	return allocated;
1071 }
1072 
1073 static unsigned io_zcrx_refill_slow(struct page_pool *pp, struct io_zcrx_ifq *ifq,
1074 				    netmem_ref *netmems, unsigned to_alloc)
1075 {
1076 	struct io_zcrx_area *area = ifq->area;
1077 	unsigned allocated = 0;
1078 
1079 	guard(spinlock_bh)(&area->freelist_lock);
1080 
1081 	for (allocated = 0; allocated < to_alloc; allocated++) {
1082 		struct net_iov *niov = zcrx_get_free_niov(area);
1083 
1084 		if (!niov)
1085 			break;
1086 		net_mp_niov_set_page_pool(pp, niov);
1087 		netmems[allocated] = net_iov_to_netmem(niov);
1088 	}
1089 	return allocated;
1090 }
1091 
1092 static netmem_ref io_pp_zc_alloc_netmems(struct page_pool *pp, gfp_t gfp)
1093 {
1094 	struct io_zcrx_ifq *ifq = io_pp_to_ifq(pp);
1095 	netmem_ref *netmems = pp->alloc.cache;
1096 	unsigned to_alloc = PP_ALLOC_CACHE_REFILL;
1097 	unsigned allocated;
1098 
1099 	/* pp should already be ensuring that */
1100 	if (WARN_ON_ONCE(pp->alloc.count))
1101 		return 0;
1102 
1103 	allocated = io_zcrx_ring_refill(pp, ifq, netmems, to_alloc);
1104 	if (likely(allocated))
1105 		goto out_return;
1106 
1107 	allocated = io_zcrx_refill_slow(pp, ifq, netmems, to_alloc);
1108 	if (!allocated)
1109 		return 0;
1110 out_return:
1111 	zcrx_sync_for_device(pp, ifq, netmems, allocated);
1112 	allocated--;
1113 	pp->alloc.count += allocated;
1114 	return netmems[allocated];
1115 }
1116 
1117 static bool io_pp_zc_release_netmem(struct page_pool *pp, netmem_ref netmem)
1118 {
1119 	struct net_iov *niov;
1120 
1121 	if (WARN_ON_ONCE(!netmem_is_net_iov(netmem)))
1122 		return false;
1123 
1124 	niov = netmem_to_net_iov(netmem);
1125 	net_mp_niov_clear_page_pool(niov);
1126 	io_zcrx_return_niov_freelist(niov);
1127 	return false;
1128 }
1129 
1130 static int io_pp_zc_init(struct page_pool *pp)
1131 {
1132 	struct io_zcrx_ifq *ifq = io_pp_to_ifq(pp);
1133 
1134 	if (WARN_ON_ONCE(!ifq))
1135 		return -EINVAL;
1136 	if (WARN_ON_ONCE(ifq->dev != pp->p.dev))
1137 		return -EINVAL;
1138 	if (WARN_ON_ONCE(!pp->dma_map))
1139 		return -EOPNOTSUPP;
1140 	if (pp->p.order + PAGE_SHIFT != ifq->niov_shift)
1141 		return -EINVAL;
1142 	if (pp->p.dma_dir != DMA_FROM_DEVICE)
1143 		return -EOPNOTSUPP;
1144 
1145 	refcount_inc(&ifq->refs);
1146 	return 0;
1147 }
1148 
1149 static void io_pp_zc_destroy(struct page_pool *pp)
1150 {
1151 	io_put_zcrx_ifq(io_pp_to_ifq(pp));
1152 }
1153 
1154 static int io_pp_nl_fill(void *mp_priv, struct sk_buff *rsp,
1155 			 struct netdev_rx_queue *rxq)
1156 {
1157 	struct nlattr *nest;
1158 	int type;
1159 
1160 	type = rxq ? NETDEV_A_QUEUE_IO_URING : NETDEV_A_PAGE_POOL_IO_URING;
1161 	nest = nla_nest_start(rsp, type);
1162 	if (!nest)
1163 		return -EMSGSIZE;
1164 	nla_nest_end(rsp, nest);
1165 
1166 	return 0;
1167 }
1168 
1169 static void io_pp_uninstall(void *mp_priv, struct netdev_rx_queue *rxq)
1170 {
1171 	struct pp_memory_provider_params *p = &rxq->mp_params;
1172 	struct io_zcrx_ifq *ifq = mp_priv;
1173 
1174 	io_zcrx_drop_netdev(ifq);
1175 	if (ifq->area)
1176 		io_zcrx_unmap_area(ifq, ifq->area);
1177 
1178 	p->mp_ops = NULL;
1179 	p->mp_priv = NULL;
1180 }
1181 
1182 static const struct memory_provider_ops io_uring_pp_zc_ops = {
1183 	.alloc_netmems		= io_pp_zc_alloc_netmems,
1184 	.release_netmem		= io_pp_zc_release_netmem,
1185 	.init			= io_pp_zc_init,
1186 	.destroy		= io_pp_zc_destroy,
1187 	.nl_fill		= io_pp_nl_fill,
1188 	.uninstall		= io_pp_uninstall,
1189 };
1190 
1191 static unsigned zcrx_parse_rq(netmem_ref *netmem_array, unsigned nr,
1192 			      struct io_zcrx_ifq *zcrx, struct zcrx_rq *rq)
1193 {
1194 	unsigned int mask = rq->nr_entries - 1;
1195 	unsigned int i;
1196 
1197 	nr = min(nr, zcrx_rq_entries(rq));
1198 	for (i = 0; i < nr; i++) {
1199 		struct io_uring_zcrx_rqe *rqe = zcrx_next_rqe(rq, mask);
1200 		struct net_iov *niov;
1201 
1202 		if (!io_parse_rqe(rqe, zcrx, &niov))
1203 			break;
1204 		netmem_array[i] = net_iov_to_netmem(niov);
1205 	}
1206 
1207 	smp_store_release(&rq->ring->head, rq->cached_head);
1208 	return i;
1209 }
1210 
1211 #define ZCRX_FLUSH_BATCH 32
1212 
1213 static void zcrx_return_buffers(netmem_ref *netmems, unsigned nr)
1214 {
1215 	unsigned i;
1216 
1217 	for (i = 0; i < nr; i++) {
1218 		netmem_ref netmem = netmems[i];
1219 		struct net_iov *niov = netmem_to_net_iov(netmem);
1220 
1221 		if (!io_zcrx_put_niov_uref(niov))
1222 			continue;
1223 		if (!page_pool_unref_and_test(netmem))
1224 			continue;
1225 		io_zcrx_return_niov(niov);
1226 	}
1227 }
1228 
1229 static int zcrx_flush_rq(struct io_ring_ctx *ctx, struct io_zcrx_ifq *zcrx,
1230 			 struct zcrx_ctrl *ctrl)
1231 {
1232 	struct zcrx_ctrl_flush_rq *frq = &ctrl->zc_flush;
1233 	netmem_ref netmems[ZCRX_FLUSH_BATCH];
1234 	unsigned total = 0;
1235 	unsigned nr;
1236 
1237 	if (!mem_is_zero(&frq->__resv, sizeof(frq->__resv)))
1238 		return -EINVAL;
1239 
1240 	do {
1241 		struct zcrx_rq *rq = &zcrx->rq;
1242 
1243 		scoped_guard(spinlock_bh, &rq->lock) {
1244 			nr = zcrx_parse_rq(netmems, ZCRX_FLUSH_BATCH, zcrx, rq);
1245 			zcrx_return_buffers(netmems, nr);
1246 		}
1247 
1248 		total += nr;
1249 
1250 		if (fatal_signal_pending(current))
1251 			break;
1252 		cond_resched();
1253 	} while (nr == ZCRX_FLUSH_BATCH && total < zcrx->rq.nr_entries);
1254 
1255 	return 0;
1256 }
1257 
1258 int io_zcrx_ctrl(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
1259 {
1260 	struct zcrx_ctrl ctrl;
1261 	struct io_zcrx_ifq *zcrx;
1262 
1263 	BUILD_BUG_ON(sizeof(ctrl.zc_export) != sizeof(ctrl.zc_flush));
1264 
1265 	if (nr_args)
1266 		return -EINVAL;
1267 	if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1268 		return -EFAULT;
1269 	if (!mem_is_zero(&ctrl.__resv, sizeof(ctrl.__resv)))
1270 		return -EFAULT;
1271 
1272 	zcrx = xa_load(&ctx->zcrx_ctxs, ctrl.zcrx_id);
1273 	if (!zcrx)
1274 		return -ENXIO;
1275 
1276 	switch (ctrl.op) {
1277 	case ZCRX_CTRL_FLUSH_RQ:
1278 		return zcrx_flush_rq(ctx, zcrx, &ctrl);
1279 	case ZCRX_CTRL_EXPORT:
1280 		return zcrx_export(ctx, zcrx, &ctrl, arg);
1281 	}
1282 
1283 	return -EOPNOTSUPP;
1284 }
1285 
1286 static bool io_zcrx_queue_cqe(struct io_kiocb *req, struct net_iov *niov,
1287 			      struct io_zcrx_ifq *ifq, int off, int len)
1288 {
1289 	struct io_ring_ctx *ctx = req->ctx;
1290 	struct io_uring_zcrx_cqe *rcqe;
1291 	struct io_zcrx_area *area;
1292 	struct io_uring_cqe *cqe;
1293 	u64 offset;
1294 
1295 	if (!io_defer_get_uncommited_cqe(ctx, &cqe))
1296 		return false;
1297 
1298 	cqe->user_data = req->cqe.user_data;
1299 	cqe->res = len;
1300 	cqe->flags = IORING_CQE_F_MORE;
1301 	if (ctx->flags & IORING_SETUP_CQE_MIXED)
1302 		cqe->flags |= IORING_CQE_F_32;
1303 
1304 	area = io_zcrx_iov_to_area(niov);
1305 	offset = off + (net_iov_idx(niov) << ifq->niov_shift);
1306 	rcqe = (struct io_uring_zcrx_cqe *)(cqe + 1);
1307 	rcqe->off = offset + ((u64)area->area_id << IORING_ZCRX_AREA_SHIFT);
1308 	rcqe->__pad = 0;
1309 	return true;
1310 }
1311 
1312 static struct net_iov *io_alloc_fallback_niov(struct io_zcrx_ifq *ifq)
1313 {
1314 	struct io_zcrx_area *area = ifq->area;
1315 	struct net_iov *niov = NULL;
1316 
1317 	if (!ifq->kern_readable)
1318 		return NULL;
1319 
1320 	scoped_guard(spinlock_bh, &area->freelist_lock)
1321 		niov = zcrx_get_free_niov(area);
1322 
1323 	if (niov)
1324 		page_pool_fragment_netmem(net_iov_to_netmem(niov), 1);
1325 	return niov;
1326 }
1327 
1328 struct io_copy_cache {
1329 	struct page		*page;
1330 	unsigned long		offset;
1331 	size_t			size;
1332 };
1333 
1334 static ssize_t io_copy_page(struct io_copy_cache *cc, struct page *src_page,
1335 			    unsigned int src_offset, size_t len)
1336 {
1337 	size_t copied = 0;
1338 
1339 	len = min(len, cc->size);
1340 
1341 	while (len) {
1342 		void *src_addr, *dst_addr;
1343 		struct page *dst_page = cc->page;
1344 		unsigned dst_offset = cc->offset;
1345 		size_t n = len;
1346 
1347 		if (folio_test_partial_kmap(page_folio(dst_page)) ||
1348 		    folio_test_partial_kmap(page_folio(src_page))) {
1349 			dst_page += dst_offset / PAGE_SIZE;
1350 			dst_offset = offset_in_page(dst_offset);
1351 			src_page += src_offset / PAGE_SIZE;
1352 			src_offset = offset_in_page(src_offset);
1353 			n = min(PAGE_SIZE - src_offset, PAGE_SIZE - dst_offset);
1354 			n = min(n, len);
1355 		}
1356 
1357 		dst_addr = kmap_local_page(dst_page) + dst_offset;
1358 		src_addr = kmap_local_page(src_page) + src_offset;
1359 
1360 		memcpy(dst_addr, src_addr, n);
1361 
1362 		kunmap_local(src_addr);
1363 		kunmap_local(dst_addr);
1364 
1365 		cc->size -= n;
1366 		cc->offset += n;
1367 		src_offset += n;
1368 		len -= n;
1369 		copied += n;
1370 	}
1371 	return copied;
1372 }
1373 
1374 static ssize_t io_zcrx_copy_chunk(struct io_kiocb *req, struct io_zcrx_ifq *ifq,
1375 				  struct page *src_page, unsigned int src_offset,
1376 				  size_t len)
1377 {
1378 	size_t copied = 0;
1379 	int ret = 0;
1380 
1381 	while (len) {
1382 		struct io_copy_cache cc;
1383 		struct net_iov *niov;
1384 		size_t n;
1385 
1386 		niov = io_alloc_fallback_niov(ifq);
1387 		if (!niov) {
1388 			ret = -ENOMEM;
1389 			break;
1390 		}
1391 
1392 		cc.page = io_zcrx_iov_page(niov);
1393 		cc.offset = 0;
1394 		cc.size = PAGE_SIZE;
1395 
1396 		n = io_copy_page(&cc, src_page, src_offset, len);
1397 
1398 		if (!io_zcrx_queue_cqe(req, niov, ifq, 0, n)) {
1399 			io_zcrx_return_niov(niov);
1400 			ret = -ENOSPC;
1401 			break;
1402 		}
1403 
1404 		io_zcrx_get_niov_uref(niov);
1405 		src_offset += n;
1406 		len -= n;
1407 		copied += n;
1408 	}
1409 
1410 	return copied ? copied : ret;
1411 }
1412 
1413 static int io_zcrx_copy_frag(struct io_kiocb *req, struct io_zcrx_ifq *ifq,
1414 			     const skb_frag_t *frag, int off, int len)
1415 {
1416 	struct page *page = skb_frag_page(frag);
1417 
1418 	return io_zcrx_copy_chunk(req, ifq, page, off + skb_frag_off(frag), len);
1419 }
1420 
1421 static int io_zcrx_recv_frag(struct io_kiocb *req, struct io_zcrx_ifq *ifq,
1422 			     const skb_frag_t *frag, int off, int len)
1423 {
1424 	struct net_iov *niov;
1425 	struct page_pool *pp;
1426 
1427 	if (unlikely(!skb_frag_is_net_iov(frag)))
1428 		return io_zcrx_copy_frag(req, ifq, frag, off, len);
1429 
1430 	niov = netmem_to_net_iov(frag->netmem);
1431 	pp = niov->desc.pp;
1432 
1433 	if (!pp || pp->mp_ops != &io_uring_pp_zc_ops || io_pp_to_ifq(pp) != ifq)
1434 		return -EFAULT;
1435 
1436 	if (!io_zcrx_queue_cqe(req, niov, ifq, off + skb_frag_off(frag), len))
1437 		return -ENOSPC;
1438 
1439 	/*
1440 	 * Prevent it from being recycled while user is accessing it.
1441 	 * It has to be done before grabbing a user reference.
1442 	 */
1443 	page_pool_ref_netmem(net_iov_to_netmem(niov));
1444 	io_zcrx_get_niov_uref(niov);
1445 	return len;
1446 }
1447 
1448 static int
1449 io_zcrx_recv_skb(read_descriptor_t *desc, struct sk_buff *skb,
1450 		 unsigned int offset, size_t len)
1451 {
1452 	struct io_zcrx_args *args = desc->arg.data;
1453 	struct io_zcrx_ifq *ifq = args->ifq;
1454 	struct io_kiocb *req = args->req;
1455 	struct sk_buff *frag_iter;
1456 	unsigned start, start_off = offset;
1457 	int i, copy, end, off;
1458 	int ret = 0;
1459 
1460 	len = min_t(size_t, len, desc->count);
1461 	/*
1462 	 * __tcp_read_sock() always calls io_zcrx_recv_skb one last time, even
1463 	 * if desc->count is already 0. This is caused by the if (offset + 1 !=
1464 	 * skb->len) check. Return early in this case to break out of
1465 	 * __tcp_read_sock().
1466 	 */
1467 	if (!len)
1468 		return 0;
1469 	if (unlikely(args->nr_skbs++ > IO_SKBS_PER_CALL_LIMIT))
1470 		return -EAGAIN;
1471 
1472 	if (unlikely(offset < skb_headlen(skb))) {
1473 		ssize_t copied;
1474 		size_t to_copy;
1475 
1476 		to_copy = min_t(size_t, skb_headlen(skb) - offset, len);
1477 		copied = io_zcrx_copy_chunk(req, ifq, virt_to_page(skb->data),
1478 					    offset_in_page(skb->data) + offset,
1479 					    to_copy);
1480 		if (copied < 0) {
1481 			ret = copied;
1482 			goto out;
1483 		}
1484 		offset += copied;
1485 		len -= copied;
1486 		if (!len)
1487 			goto out;
1488 		if (offset != skb_headlen(skb))
1489 			goto out;
1490 	}
1491 
1492 	start = skb_headlen(skb);
1493 
1494 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1495 		const skb_frag_t *frag;
1496 
1497 		if (WARN_ON(start > offset + len))
1498 			return -EFAULT;
1499 
1500 		frag = &skb_shinfo(skb)->frags[i];
1501 		end = start + skb_frag_size(frag);
1502 
1503 		if (offset < end) {
1504 			copy = end - offset;
1505 			if (copy > len)
1506 				copy = len;
1507 
1508 			off = offset - start;
1509 			ret = io_zcrx_recv_frag(req, ifq, frag, off, copy);
1510 			if (ret < 0)
1511 				goto out;
1512 
1513 			offset += ret;
1514 			len -= ret;
1515 			if (len == 0 || ret != copy)
1516 				goto out;
1517 		}
1518 		start = end;
1519 	}
1520 
1521 	skb_walk_frags(skb, frag_iter) {
1522 		if (WARN_ON(start > offset + len))
1523 			return -EFAULT;
1524 
1525 		end = start + frag_iter->len;
1526 		if (offset < end) {
1527 			size_t count;
1528 
1529 			copy = end - offset;
1530 			if (copy > len)
1531 				copy = len;
1532 
1533 			off = offset - start;
1534 			count = desc->count;
1535 			ret = io_zcrx_recv_skb(desc, frag_iter, off, copy);
1536 			desc->count = count;
1537 			if (ret < 0)
1538 				goto out;
1539 
1540 			offset += ret;
1541 			len -= ret;
1542 			if (len == 0 || ret != copy)
1543 				goto out;
1544 		}
1545 		start = end;
1546 	}
1547 
1548 out:
1549 	if (offset == start_off)
1550 		return ret;
1551 	desc->count -= (offset - start_off);
1552 	return offset - start_off;
1553 }
1554 
1555 static int io_zcrx_tcp_recvmsg(struct io_kiocb *req, struct io_zcrx_ifq *ifq,
1556 				struct sock *sk, int flags,
1557 				unsigned issue_flags, unsigned int *outlen)
1558 {
1559 	unsigned int len = *outlen;
1560 	struct io_zcrx_args args = {
1561 		.req = req,
1562 		.ifq = ifq,
1563 		.sock = sk->sk_socket,
1564 	};
1565 	read_descriptor_t rd_desc = {
1566 		.count = len ? len : UINT_MAX,
1567 		.arg.data = &args,
1568 	};
1569 	int ret;
1570 
1571 	lock_sock(sk);
1572 	ret = tcp_read_sock(sk, &rd_desc, io_zcrx_recv_skb);
1573 	if (len && ret > 0)
1574 		*outlen = len - ret;
1575 	if (ret <= 0) {
1576 		if (ret < 0 || sock_flag(sk, SOCK_DONE))
1577 			goto out;
1578 		if (sk->sk_err)
1579 			ret = sock_error(sk);
1580 		else if (sk->sk_shutdown & RCV_SHUTDOWN)
1581 			goto out;
1582 		else if (sk->sk_state == TCP_CLOSE)
1583 			ret = -ENOTCONN;
1584 		else
1585 			ret = -EAGAIN;
1586 	} else if (unlikely(args.nr_skbs > IO_SKBS_PER_CALL_LIMIT) &&
1587 		   (issue_flags & IO_URING_F_MULTISHOT)) {
1588 		ret = IOU_REQUEUE;
1589 	} else if (sock_flag(sk, SOCK_DONE)) {
1590 		/* Make it to retry until it finally gets 0. */
1591 		if (issue_flags & IO_URING_F_MULTISHOT)
1592 			ret = IOU_REQUEUE;
1593 		else
1594 			ret = -EAGAIN;
1595 	}
1596 out:
1597 	release_sock(sk);
1598 	return ret;
1599 }
1600 
1601 int io_zcrx_recv(struct io_kiocb *req, struct io_zcrx_ifq *ifq,
1602 		 struct socket *sock, unsigned int flags,
1603 		 unsigned issue_flags, unsigned int *len)
1604 {
1605 	struct sock *sk = sock->sk;
1606 	const struct proto *prot = READ_ONCE(sk->sk_prot);
1607 
1608 	if (prot->recvmsg != tcp_recvmsg)
1609 		return -EPROTONOSUPPORT;
1610 
1611 	sock_rps_record_flow(sk);
1612 	return io_zcrx_tcp_recvmsg(req, ifq, sk, flags, issue_flags, len);
1613 }
1614