xref: /openbmc/linux/crypto/af_alg.c (revision 6d04fe15)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * af_alg: User-space algorithm interface
4  *
5  * This file provides the user-space API for algorithms.
6  *
7  * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
8  */
9 
10 #include <linux/atomic.h>
11 #include <crypto/if_alg.h>
12 #include <linux/crypto.h>
13 #include <linux/init.h>
14 #include <linux/kernel.h>
15 #include <linux/list.h>
16 #include <linux/module.h>
17 #include <linux/net.h>
18 #include <linux/rwsem.h>
19 #include <linux/sched/signal.h>
20 #include <linux/security.h>
21 
22 struct alg_type_list {
23 	const struct af_alg_type *type;
24 	struct list_head list;
25 };
26 
27 static atomic_long_t alg_memory_allocated;
28 
29 static struct proto alg_proto = {
30 	.name			= "ALG",
31 	.owner			= THIS_MODULE,
32 	.memory_allocated	= &alg_memory_allocated,
33 	.obj_size		= sizeof(struct alg_sock),
34 };
35 
36 static LIST_HEAD(alg_types);
37 static DECLARE_RWSEM(alg_types_sem);
38 
39 static const struct af_alg_type *alg_get_type(const char *name)
40 {
41 	const struct af_alg_type *type = ERR_PTR(-ENOENT);
42 	struct alg_type_list *node;
43 
44 	down_read(&alg_types_sem);
45 	list_for_each_entry(node, &alg_types, list) {
46 		if (strcmp(node->type->name, name))
47 			continue;
48 
49 		if (try_module_get(node->type->owner))
50 			type = node->type;
51 		break;
52 	}
53 	up_read(&alg_types_sem);
54 
55 	return type;
56 }
57 
58 int af_alg_register_type(const struct af_alg_type *type)
59 {
60 	struct alg_type_list *node;
61 	int err = -EEXIST;
62 
63 	down_write(&alg_types_sem);
64 	list_for_each_entry(node, &alg_types, list) {
65 		if (!strcmp(node->type->name, type->name))
66 			goto unlock;
67 	}
68 
69 	node = kmalloc(sizeof(*node), GFP_KERNEL);
70 	err = -ENOMEM;
71 	if (!node)
72 		goto unlock;
73 
74 	type->ops->owner = THIS_MODULE;
75 	if (type->ops_nokey)
76 		type->ops_nokey->owner = THIS_MODULE;
77 	node->type = type;
78 	list_add(&node->list, &alg_types);
79 	err = 0;
80 
81 unlock:
82 	up_write(&alg_types_sem);
83 
84 	return err;
85 }
86 EXPORT_SYMBOL_GPL(af_alg_register_type);
87 
88 int af_alg_unregister_type(const struct af_alg_type *type)
89 {
90 	struct alg_type_list *node;
91 	int err = -ENOENT;
92 
93 	down_write(&alg_types_sem);
94 	list_for_each_entry(node, &alg_types, list) {
95 		if (strcmp(node->type->name, type->name))
96 			continue;
97 
98 		list_del(&node->list);
99 		kfree(node);
100 		err = 0;
101 		break;
102 	}
103 	up_write(&alg_types_sem);
104 
105 	return err;
106 }
107 EXPORT_SYMBOL_GPL(af_alg_unregister_type);
108 
109 static void alg_do_release(const struct af_alg_type *type, void *private)
110 {
111 	if (!type)
112 		return;
113 
114 	type->release(private);
115 	module_put(type->owner);
116 }
117 
118 int af_alg_release(struct socket *sock)
119 {
120 	if (sock->sk) {
121 		sock_put(sock->sk);
122 		sock->sk = NULL;
123 	}
124 	return 0;
125 }
126 EXPORT_SYMBOL_GPL(af_alg_release);
127 
128 void af_alg_release_parent(struct sock *sk)
129 {
130 	struct alg_sock *ask = alg_sk(sk);
131 	unsigned int nokey = atomic_read(&ask->nokey_refcnt);
132 
133 	sk = ask->parent;
134 	ask = alg_sk(sk);
135 
136 	if (nokey)
137 		atomic_dec(&ask->nokey_refcnt);
138 
139 	if (atomic_dec_and_test(&ask->refcnt))
140 		sock_put(sk);
141 }
142 EXPORT_SYMBOL_GPL(af_alg_release_parent);
143 
144 static int alg_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
145 {
146 	const u32 allowed = CRYPTO_ALG_KERN_DRIVER_ONLY;
147 	struct sock *sk = sock->sk;
148 	struct alg_sock *ask = alg_sk(sk);
149 	struct sockaddr_alg *sa = (void *)uaddr;
150 	const struct af_alg_type *type;
151 	void *private;
152 	int err;
153 
154 	if (sock->state == SS_CONNECTED)
155 		return -EINVAL;
156 
157 	if (addr_len < sizeof(*sa))
158 		return -EINVAL;
159 
160 	/* If caller uses non-allowed flag, return error. */
161 	if ((sa->salg_feat & ~allowed) || (sa->salg_mask & ~allowed))
162 		return -EINVAL;
163 
164 	sa->salg_type[sizeof(sa->salg_type) - 1] = 0;
165 	sa->salg_name[sizeof(sa->salg_name) + addr_len - sizeof(*sa) - 1] = 0;
166 
167 	type = alg_get_type(sa->salg_type);
168 	if (PTR_ERR(type) == -ENOENT) {
169 		request_module("algif-%s", sa->salg_type);
170 		type = alg_get_type(sa->salg_type);
171 	}
172 
173 	if (IS_ERR(type))
174 		return PTR_ERR(type);
175 
176 	private = type->bind(sa->salg_name, sa->salg_feat, sa->salg_mask);
177 	if (IS_ERR(private)) {
178 		module_put(type->owner);
179 		return PTR_ERR(private);
180 	}
181 
182 	err = -EBUSY;
183 	lock_sock(sk);
184 	if (atomic_read(&ask->refcnt))
185 		goto unlock;
186 
187 	swap(ask->type, type);
188 	swap(ask->private, private);
189 
190 	err = 0;
191 
192 unlock:
193 	release_sock(sk);
194 
195 	alg_do_release(type, private);
196 
197 	return err;
198 }
199 
200 static int alg_setkey(struct sock *sk, sockptr_t ukey, unsigned int keylen)
201 {
202 	struct alg_sock *ask = alg_sk(sk);
203 	const struct af_alg_type *type = ask->type;
204 	u8 *key;
205 	int err;
206 
207 	key = sock_kmalloc(sk, keylen, GFP_KERNEL);
208 	if (!key)
209 		return -ENOMEM;
210 
211 	err = -EFAULT;
212 	if (copy_from_sockptr(key, ukey, keylen))
213 		goto out;
214 
215 	err = type->setkey(ask->private, key, keylen);
216 
217 out:
218 	sock_kzfree_s(sk, key, keylen);
219 
220 	return err;
221 }
222 
223 static int alg_setsockopt(struct socket *sock, int level, int optname,
224 			  sockptr_t optval, unsigned int optlen)
225 {
226 	struct sock *sk = sock->sk;
227 	struct alg_sock *ask = alg_sk(sk);
228 	const struct af_alg_type *type;
229 	int err = -EBUSY;
230 
231 	lock_sock(sk);
232 	if (atomic_read(&ask->refcnt) != atomic_read(&ask->nokey_refcnt))
233 		goto unlock;
234 
235 	type = ask->type;
236 
237 	err = -ENOPROTOOPT;
238 	if (level != SOL_ALG || !type)
239 		goto unlock;
240 
241 	switch (optname) {
242 	case ALG_SET_KEY:
243 		if (sock->state == SS_CONNECTED)
244 			goto unlock;
245 		if (!type->setkey)
246 			goto unlock;
247 
248 		err = alg_setkey(sk, optval, optlen);
249 		break;
250 	case ALG_SET_AEAD_AUTHSIZE:
251 		if (sock->state == SS_CONNECTED)
252 			goto unlock;
253 		if (!type->setauthsize)
254 			goto unlock;
255 		err = type->setauthsize(ask->private, optlen);
256 	}
257 
258 unlock:
259 	release_sock(sk);
260 
261 	return err;
262 }
263 
264 int af_alg_accept(struct sock *sk, struct socket *newsock, bool kern)
265 {
266 	struct alg_sock *ask = alg_sk(sk);
267 	const struct af_alg_type *type;
268 	struct sock *sk2;
269 	unsigned int nokey;
270 	int err;
271 
272 	lock_sock(sk);
273 	type = ask->type;
274 
275 	err = -EINVAL;
276 	if (!type)
277 		goto unlock;
278 
279 	sk2 = sk_alloc(sock_net(sk), PF_ALG, GFP_KERNEL, &alg_proto, kern);
280 	err = -ENOMEM;
281 	if (!sk2)
282 		goto unlock;
283 
284 	sock_init_data(newsock, sk2);
285 	security_sock_graft(sk2, newsock);
286 	security_sk_clone(sk, sk2);
287 
288 	err = type->accept(ask->private, sk2);
289 
290 	nokey = err == -ENOKEY;
291 	if (nokey && type->accept_nokey)
292 		err = type->accept_nokey(ask->private, sk2);
293 
294 	if (err)
295 		goto unlock;
296 
297 	if (atomic_inc_return_relaxed(&ask->refcnt) == 1)
298 		sock_hold(sk);
299 	if (nokey) {
300 		atomic_inc(&ask->nokey_refcnt);
301 		atomic_set(&alg_sk(sk2)->nokey_refcnt, 1);
302 	}
303 	alg_sk(sk2)->parent = sk;
304 	alg_sk(sk2)->type = type;
305 
306 	newsock->ops = type->ops;
307 	newsock->state = SS_CONNECTED;
308 
309 	if (nokey)
310 		newsock->ops = type->ops_nokey;
311 
312 	err = 0;
313 
314 unlock:
315 	release_sock(sk);
316 
317 	return err;
318 }
319 EXPORT_SYMBOL_GPL(af_alg_accept);
320 
321 static int alg_accept(struct socket *sock, struct socket *newsock, int flags,
322 		      bool kern)
323 {
324 	return af_alg_accept(sock->sk, newsock, kern);
325 }
326 
327 static const struct proto_ops alg_proto_ops = {
328 	.family		=	PF_ALG,
329 	.owner		=	THIS_MODULE,
330 
331 	.connect	=	sock_no_connect,
332 	.socketpair	=	sock_no_socketpair,
333 	.getname	=	sock_no_getname,
334 	.ioctl		=	sock_no_ioctl,
335 	.listen		=	sock_no_listen,
336 	.shutdown	=	sock_no_shutdown,
337 	.mmap		=	sock_no_mmap,
338 	.sendpage	=	sock_no_sendpage,
339 	.sendmsg	=	sock_no_sendmsg,
340 	.recvmsg	=	sock_no_recvmsg,
341 
342 	.bind		=	alg_bind,
343 	.release	=	af_alg_release,
344 	.setsockopt	=	alg_setsockopt,
345 	.accept		=	alg_accept,
346 };
347 
348 static void alg_sock_destruct(struct sock *sk)
349 {
350 	struct alg_sock *ask = alg_sk(sk);
351 
352 	alg_do_release(ask->type, ask->private);
353 }
354 
355 static int alg_create(struct net *net, struct socket *sock, int protocol,
356 		      int kern)
357 {
358 	struct sock *sk;
359 	int err;
360 
361 	if (sock->type != SOCK_SEQPACKET)
362 		return -ESOCKTNOSUPPORT;
363 	if (protocol != 0)
364 		return -EPROTONOSUPPORT;
365 
366 	err = -ENOMEM;
367 	sk = sk_alloc(net, PF_ALG, GFP_KERNEL, &alg_proto, kern);
368 	if (!sk)
369 		goto out;
370 
371 	sock->ops = &alg_proto_ops;
372 	sock_init_data(sock, sk);
373 
374 	sk->sk_destruct = alg_sock_destruct;
375 
376 	return 0;
377 out:
378 	return err;
379 }
380 
381 static const struct net_proto_family alg_family = {
382 	.family	=	PF_ALG,
383 	.create	=	alg_create,
384 	.owner	=	THIS_MODULE,
385 };
386 
387 int af_alg_make_sg(struct af_alg_sgl *sgl, struct iov_iter *iter, int len)
388 {
389 	size_t off;
390 	ssize_t n;
391 	int npages, i;
392 
393 	n = iov_iter_get_pages(iter, sgl->pages, len, ALG_MAX_PAGES, &off);
394 	if (n < 0)
395 		return n;
396 
397 	npages = (off + n + PAGE_SIZE - 1) >> PAGE_SHIFT;
398 	if (WARN_ON(npages == 0))
399 		return -EINVAL;
400 	/* Add one extra for linking */
401 	sg_init_table(sgl->sg, npages + 1);
402 
403 	for (i = 0, len = n; i < npages; i++) {
404 		int plen = min_t(int, len, PAGE_SIZE - off);
405 
406 		sg_set_page(sgl->sg + i, sgl->pages[i], plen, off);
407 
408 		off = 0;
409 		len -= plen;
410 	}
411 	sg_mark_end(sgl->sg + npages - 1);
412 	sgl->npages = npages;
413 
414 	return n;
415 }
416 EXPORT_SYMBOL_GPL(af_alg_make_sg);
417 
418 static void af_alg_link_sg(struct af_alg_sgl *sgl_prev,
419 			   struct af_alg_sgl *sgl_new)
420 {
421 	sg_unmark_end(sgl_prev->sg + sgl_prev->npages - 1);
422 	sg_chain(sgl_prev->sg, sgl_prev->npages + 1, sgl_new->sg);
423 }
424 
425 void af_alg_free_sg(struct af_alg_sgl *sgl)
426 {
427 	int i;
428 
429 	for (i = 0; i < sgl->npages; i++)
430 		put_page(sgl->pages[i]);
431 }
432 EXPORT_SYMBOL_GPL(af_alg_free_sg);
433 
434 static int af_alg_cmsg_send(struct msghdr *msg, struct af_alg_control *con)
435 {
436 	struct cmsghdr *cmsg;
437 
438 	for_each_cmsghdr(cmsg, msg) {
439 		if (!CMSG_OK(msg, cmsg))
440 			return -EINVAL;
441 		if (cmsg->cmsg_level != SOL_ALG)
442 			continue;
443 
444 		switch (cmsg->cmsg_type) {
445 		case ALG_SET_IV:
446 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(*con->iv)))
447 				return -EINVAL;
448 			con->iv = (void *)CMSG_DATA(cmsg);
449 			if (cmsg->cmsg_len < CMSG_LEN(con->iv->ivlen +
450 						      sizeof(*con->iv)))
451 				return -EINVAL;
452 			break;
453 
454 		case ALG_SET_OP:
455 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
456 				return -EINVAL;
457 			con->op = *(u32 *)CMSG_DATA(cmsg);
458 			break;
459 
460 		case ALG_SET_AEAD_ASSOCLEN:
461 			if (cmsg->cmsg_len < CMSG_LEN(sizeof(u32)))
462 				return -EINVAL;
463 			con->aead_assoclen = *(u32 *)CMSG_DATA(cmsg);
464 			break;
465 
466 		default:
467 			return -EINVAL;
468 		}
469 	}
470 
471 	return 0;
472 }
473 
474 /**
475  * af_alg_alloc_tsgl - allocate the TX SGL
476  *
477  * @sk socket of connection to user space
478  * @return: 0 upon success, < 0 upon error
479  */
480 static int af_alg_alloc_tsgl(struct sock *sk)
481 {
482 	struct alg_sock *ask = alg_sk(sk);
483 	struct af_alg_ctx *ctx = ask->private;
484 	struct af_alg_tsgl *sgl;
485 	struct scatterlist *sg = NULL;
486 
487 	sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl, list);
488 	if (!list_empty(&ctx->tsgl_list))
489 		sg = sgl->sg;
490 
491 	if (!sg || sgl->cur >= MAX_SGL_ENTS) {
492 		sgl = sock_kmalloc(sk,
493 				   struct_size(sgl, sg, (MAX_SGL_ENTS + 1)),
494 				   GFP_KERNEL);
495 		if (!sgl)
496 			return -ENOMEM;
497 
498 		sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
499 		sgl->cur = 0;
500 
501 		if (sg)
502 			sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
503 
504 		list_add_tail(&sgl->list, &ctx->tsgl_list);
505 	}
506 
507 	return 0;
508 }
509 
510 /**
511  * aead_count_tsgl - Count number of TX SG entries
512  *
513  * The counting starts from the beginning of the SGL to @bytes. If
514  * an offset is provided, the counting of the SG entries starts at the offset.
515  *
516  * @sk socket of connection to user space
517  * @bytes Count the number of SG entries holding given number of bytes.
518  * @offset Start the counting of SG entries from the given offset.
519  * @return Number of TX SG entries found given the constraints
520  */
521 unsigned int af_alg_count_tsgl(struct sock *sk, size_t bytes, size_t offset)
522 {
523 	const struct alg_sock *ask = alg_sk(sk);
524 	const struct af_alg_ctx *ctx = ask->private;
525 	const struct af_alg_tsgl *sgl;
526 	unsigned int i;
527 	unsigned int sgl_count = 0;
528 
529 	if (!bytes)
530 		return 0;
531 
532 	list_for_each_entry(sgl, &ctx->tsgl_list, list) {
533 		const struct scatterlist *sg = sgl->sg;
534 
535 		for (i = 0; i < sgl->cur; i++) {
536 			size_t bytes_count;
537 
538 			/* Skip offset */
539 			if (offset >= sg[i].length) {
540 				offset -= sg[i].length;
541 				bytes -= sg[i].length;
542 				continue;
543 			}
544 
545 			bytes_count = sg[i].length - offset;
546 
547 			offset = 0;
548 			sgl_count++;
549 
550 			/* If we have seen requested number of bytes, stop */
551 			if (bytes_count >= bytes)
552 				return sgl_count;
553 
554 			bytes -= bytes_count;
555 		}
556 	}
557 
558 	return sgl_count;
559 }
560 EXPORT_SYMBOL_GPL(af_alg_count_tsgl);
561 
562 /**
563  * aead_pull_tsgl - Release the specified buffers from TX SGL
564  *
565  * If @dst is non-null, reassign the pages to dst. The caller must release
566  * the pages. If @dst_offset is given only reassign the pages to @dst starting
567  * at the @dst_offset (byte). The caller must ensure that @dst is large
568  * enough (e.g. by using af_alg_count_tsgl with the same offset).
569  *
570  * @sk socket of connection to user space
571  * @used Number of bytes to pull from TX SGL
572  * @dst If non-NULL, buffer is reassigned to dst SGL instead of releasing. The
573  *	caller must release the buffers in dst.
574  * @dst_offset Reassign the TX SGL from given offset. All buffers before
575  *	       reaching the offset is released.
576  */
577 void af_alg_pull_tsgl(struct sock *sk, size_t used, struct scatterlist *dst,
578 		      size_t dst_offset)
579 {
580 	struct alg_sock *ask = alg_sk(sk);
581 	struct af_alg_ctx *ctx = ask->private;
582 	struct af_alg_tsgl *sgl;
583 	struct scatterlist *sg;
584 	unsigned int i, j = 0;
585 
586 	while (!list_empty(&ctx->tsgl_list)) {
587 		sgl = list_first_entry(&ctx->tsgl_list, struct af_alg_tsgl,
588 				       list);
589 		sg = sgl->sg;
590 
591 		for (i = 0; i < sgl->cur; i++) {
592 			size_t plen = min_t(size_t, used, sg[i].length);
593 			struct page *page = sg_page(sg + i);
594 
595 			if (!page)
596 				continue;
597 
598 			/*
599 			 * Assumption: caller created af_alg_count_tsgl(len)
600 			 * SG entries in dst.
601 			 */
602 			if (dst) {
603 				if (dst_offset >= plen) {
604 					/* discard page before offset */
605 					dst_offset -= plen;
606 				} else {
607 					/* reassign page to dst after offset */
608 					get_page(page);
609 					sg_set_page(dst + j, page,
610 						    plen - dst_offset,
611 						    sg[i].offset + dst_offset);
612 					dst_offset = 0;
613 					j++;
614 				}
615 			}
616 
617 			sg[i].length -= plen;
618 			sg[i].offset += plen;
619 
620 			used -= plen;
621 			ctx->used -= plen;
622 
623 			if (sg[i].length)
624 				return;
625 
626 			put_page(page);
627 			sg_assign_page(sg + i, NULL);
628 		}
629 
630 		list_del(&sgl->list);
631 		sock_kfree_s(sk, sgl, struct_size(sgl, sg, MAX_SGL_ENTS + 1));
632 	}
633 
634 	if (!ctx->used)
635 		ctx->merge = 0;
636 }
637 EXPORT_SYMBOL_GPL(af_alg_pull_tsgl);
638 
639 /**
640  * af_alg_free_areq_sgls - Release TX and RX SGLs of the request
641  *
642  * @areq Request holding the TX and RX SGL
643  */
644 static void af_alg_free_areq_sgls(struct af_alg_async_req *areq)
645 {
646 	struct sock *sk = areq->sk;
647 	struct alg_sock *ask = alg_sk(sk);
648 	struct af_alg_ctx *ctx = ask->private;
649 	struct af_alg_rsgl *rsgl, *tmp;
650 	struct scatterlist *tsgl;
651 	struct scatterlist *sg;
652 	unsigned int i;
653 
654 	list_for_each_entry_safe(rsgl, tmp, &areq->rsgl_list, list) {
655 		atomic_sub(rsgl->sg_num_bytes, &ctx->rcvused);
656 		af_alg_free_sg(&rsgl->sgl);
657 		list_del(&rsgl->list);
658 		if (rsgl != &areq->first_rsgl)
659 			sock_kfree_s(sk, rsgl, sizeof(*rsgl));
660 	}
661 
662 	tsgl = areq->tsgl;
663 	if (tsgl) {
664 		for_each_sg(tsgl, sg, areq->tsgl_entries, i) {
665 			if (!sg_page(sg))
666 				continue;
667 			put_page(sg_page(sg));
668 		}
669 
670 		sock_kfree_s(sk, tsgl, areq->tsgl_entries * sizeof(*tsgl));
671 	}
672 }
673 
674 /**
675  * af_alg_wait_for_wmem - wait for availability of writable memory
676  *
677  * @sk socket of connection to user space
678  * @flags If MSG_DONTWAIT is set, then only report if function would sleep
679  * @return 0 when writable memory is available, < 0 upon error
680  */
681 static int af_alg_wait_for_wmem(struct sock *sk, unsigned int flags)
682 {
683 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
684 	int err = -ERESTARTSYS;
685 	long timeout;
686 
687 	if (flags & MSG_DONTWAIT)
688 		return -EAGAIN;
689 
690 	sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
691 
692 	add_wait_queue(sk_sleep(sk), &wait);
693 	for (;;) {
694 		if (signal_pending(current))
695 			break;
696 		timeout = MAX_SCHEDULE_TIMEOUT;
697 		if (sk_wait_event(sk, &timeout, af_alg_writable(sk), &wait)) {
698 			err = 0;
699 			break;
700 		}
701 	}
702 	remove_wait_queue(sk_sleep(sk), &wait);
703 
704 	return err;
705 }
706 
707 /**
708  * af_alg_wmem_wakeup - wakeup caller when writable memory is available
709  *
710  * @sk socket of connection to user space
711  */
712 void af_alg_wmem_wakeup(struct sock *sk)
713 {
714 	struct socket_wq *wq;
715 
716 	if (!af_alg_writable(sk))
717 		return;
718 
719 	rcu_read_lock();
720 	wq = rcu_dereference(sk->sk_wq);
721 	if (skwq_has_sleeper(wq))
722 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
723 							   EPOLLRDNORM |
724 							   EPOLLRDBAND);
725 	sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
726 	rcu_read_unlock();
727 }
728 EXPORT_SYMBOL_GPL(af_alg_wmem_wakeup);
729 
730 /**
731  * af_alg_wait_for_data - wait for availability of TX data
732  *
733  * @sk socket of connection to user space
734  * @flags If MSG_DONTWAIT is set, then only report if function would sleep
735  * @return 0 when writable memory is available, < 0 upon error
736  */
737 int af_alg_wait_for_data(struct sock *sk, unsigned flags)
738 {
739 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
740 	struct alg_sock *ask = alg_sk(sk);
741 	struct af_alg_ctx *ctx = ask->private;
742 	long timeout;
743 	int err = -ERESTARTSYS;
744 
745 	if (flags & MSG_DONTWAIT)
746 		return -EAGAIN;
747 
748 	sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
749 
750 	add_wait_queue(sk_sleep(sk), &wait);
751 	for (;;) {
752 		if (signal_pending(current))
753 			break;
754 		timeout = MAX_SCHEDULE_TIMEOUT;
755 		if (sk_wait_event(sk, &timeout, (ctx->used || !ctx->more),
756 				  &wait)) {
757 			err = 0;
758 			break;
759 		}
760 	}
761 	remove_wait_queue(sk_sleep(sk), &wait);
762 
763 	sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
764 
765 	return err;
766 }
767 EXPORT_SYMBOL_GPL(af_alg_wait_for_data);
768 
769 /**
770  * af_alg_data_wakeup - wakeup caller when new data can be sent to kernel
771  *
772  * @sk socket of connection to user space
773  */
774 static void af_alg_data_wakeup(struct sock *sk)
775 {
776 	struct alg_sock *ask = alg_sk(sk);
777 	struct af_alg_ctx *ctx = ask->private;
778 	struct socket_wq *wq;
779 
780 	if (!ctx->used)
781 		return;
782 
783 	rcu_read_lock();
784 	wq = rcu_dereference(sk->sk_wq);
785 	if (skwq_has_sleeper(wq))
786 		wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
787 							   EPOLLRDNORM |
788 							   EPOLLRDBAND);
789 	sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
790 	rcu_read_unlock();
791 }
792 
793 /**
794  * af_alg_sendmsg - implementation of sendmsg system call handler
795  *
796  * The sendmsg system call handler obtains the user data and stores it
797  * in ctx->tsgl_list. This implies allocation of the required numbers of
798  * struct af_alg_tsgl.
799  *
800  * In addition, the ctx is filled with the information sent via CMSG.
801  *
802  * @sock socket of connection to user space
803  * @msg message from user space
804  * @size size of message from user space
805  * @ivsize the size of the IV for the cipher operation to verify that the
806  *	   user-space-provided IV has the right size
807  * @return the number of copied data upon success, < 0 upon error
808  */
809 int af_alg_sendmsg(struct socket *sock, struct msghdr *msg, size_t size,
810 		   unsigned int ivsize)
811 {
812 	struct sock *sk = sock->sk;
813 	struct alg_sock *ask = alg_sk(sk);
814 	struct af_alg_ctx *ctx = ask->private;
815 	struct af_alg_tsgl *sgl;
816 	struct af_alg_control con = {};
817 	long copied = 0;
818 	bool enc = false;
819 	bool init = false;
820 	int err = 0;
821 
822 	if (msg->msg_controllen) {
823 		err = af_alg_cmsg_send(msg, &con);
824 		if (err)
825 			return err;
826 
827 		init = true;
828 		switch (con.op) {
829 		case ALG_OP_ENCRYPT:
830 			enc = true;
831 			break;
832 		case ALG_OP_DECRYPT:
833 			enc = false;
834 			break;
835 		default:
836 			return -EINVAL;
837 		}
838 
839 		if (con.iv && con.iv->ivlen != ivsize)
840 			return -EINVAL;
841 	}
842 
843 	lock_sock(sk);
844 	if (!ctx->more && ctx->used) {
845 		err = -EINVAL;
846 		goto unlock;
847 	}
848 
849 	if (init) {
850 		ctx->enc = enc;
851 		if (con.iv)
852 			memcpy(ctx->iv, con.iv->iv, ivsize);
853 
854 		ctx->aead_assoclen = con.aead_assoclen;
855 	}
856 
857 	while (size) {
858 		struct scatterlist *sg;
859 		size_t len = size;
860 		size_t plen;
861 
862 		/* use the existing memory in an allocated page */
863 		if (ctx->merge) {
864 			sgl = list_entry(ctx->tsgl_list.prev,
865 					 struct af_alg_tsgl, list);
866 			sg = sgl->sg + sgl->cur - 1;
867 			len = min_t(size_t, len,
868 				    PAGE_SIZE - sg->offset - sg->length);
869 
870 			err = memcpy_from_msg(page_address(sg_page(sg)) +
871 					      sg->offset + sg->length,
872 					      msg, len);
873 			if (err)
874 				goto unlock;
875 
876 			sg->length += len;
877 			ctx->merge = (sg->offset + sg->length) &
878 				     (PAGE_SIZE - 1);
879 
880 			ctx->used += len;
881 			copied += len;
882 			size -= len;
883 			continue;
884 		}
885 
886 		if (!af_alg_writable(sk)) {
887 			err = af_alg_wait_for_wmem(sk, msg->msg_flags);
888 			if (err)
889 				goto unlock;
890 		}
891 
892 		/* allocate a new page */
893 		len = min_t(unsigned long, len, af_alg_sndbuf(sk));
894 
895 		err = af_alg_alloc_tsgl(sk);
896 		if (err)
897 			goto unlock;
898 
899 		sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl,
900 				 list);
901 		sg = sgl->sg;
902 		if (sgl->cur)
903 			sg_unmark_end(sg + sgl->cur - 1);
904 
905 		do {
906 			unsigned int i = sgl->cur;
907 
908 			plen = min_t(size_t, len, PAGE_SIZE);
909 
910 			sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
911 			if (!sg_page(sg + i)) {
912 				err = -ENOMEM;
913 				goto unlock;
914 			}
915 
916 			err = memcpy_from_msg(page_address(sg_page(sg + i)),
917 					      msg, plen);
918 			if (err) {
919 				__free_page(sg_page(sg + i));
920 				sg_assign_page(sg + i, NULL);
921 				goto unlock;
922 			}
923 
924 			sg[i].length = plen;
925 			len -= plen;
926 			ctx->used += plen;
927 			copied += plen;
928 			size -= plen;
929 			sgl->cur++;
930 		} while (len && sgl->cur < MAX_SGL_ENTS);
931 
932 		if (!size)
933 			sg_mark_end(sg + sgl->cur - 1);
934 
935 		ctx->merge = plen & (PAGE_SIZE - 1);
936 	}
937 
938 	err = 0;
939 
940 	ctx->more = msg->msg_flags & MSG_MORE;
941 
942 unlock:
943 	af_alg_data_wakeup(sk);
944 	release_sock(sk);
945 
946 	return copied ?: err;
947 }
948 EXPORT_SYMBOL_GPL(af_alg_sendmsg);
949 
950 /**
951  * af_alg_sendpage - sendpage system call handler
952  *
953  * This is a generic implementation of sendpage to fill ctx->tsgl_list.
954  */
955 ssize_t af_alg_sendpage(struct socket *sock, struct page *page,
956 			int offset, size_t size, int flags)
957 {
958 	struct sock *sk = sock->sk;
959 	struct alg_sock *ask = alg_sk(sk);
960 	struct af_alg_ctx *ctx = ask->private;
961 	struct af_alg_tsgl *sgl;
962 	int err = -EINVAL;
963 
964 	if (flags & MSG_SENDPAGE_NOTLAST)
965 		flags |= MSG_MORE;
966 
967 	lock_sock(sk);
968 	if (!ctx->more && ctx->used)
969 		goto unlock;
970 
971 	if (!size)
972 		goto done;
973 
974 	if (!af_alg_writable(sk)) {
975 		err = af_alg_wait_for_wmem(sk, flags);
976 		if (err)
977 			goto unlock;
978 	}
979 
980 	err = af_alg_alloc_tsgl(sk);
981 	if (err)
982 		goto unlock;
983 
984 	ctx->merge = 0;
985 	sgl = list_entry(ctx->tsgl_list.prev, struct af_alg_tsgl, list);
986 
987 	if (sgl->cur)
988 		sg_unmark_end(sgl->sg + sgl->cur - 1);
989 
990 	sg_mark_end(sgl->sg + sgl->cur);
991 
992 	get_page(page);
993 	sg_set_page(sgl->sg + sgl->cur, page, size, offset);
994 	sgl->cur++;
995 	ctx->used += size;
996 
997 done:
998 	ctx->more = flags & MSG_MORE;
999 
1000 unlock:
1001 	af_alg_data_wakeup(sk);
1002 	release_sock(sk);
1003 
1004 	return err ?: size;
1005 }
1006 EXPORT_SYMBOL_GPL(af_alg_sendpage);
1007 
1008 /**
1009  * af_alg_free_resources - release resources required for crypto request
1010  */
1011 void af_alg_free_resources(struct af_alg_async_req *areq)
1012 {
1013 	struct sock *sk = areq->sk;
1014 
1015 	af_alg_free_areq_sgls(areq);
1016 	sock_kfree_s(sk, areq, areq->areqlen);
1017 }
1018 EXPORT_SYMBOL_GPL(af_alg_free_resources);
1019 
1020 /**
1021  * af_alg_async_cb - AIO callback handler
1022  *
1023  * This handler cleans up the struct af_alg_async_req upon completion of the
1024  * AIO operation.
1025  *
1026  * The number of bytes to be generated with the AIO operation must be set
1027  * in areq->outlen before the AIO callback handler is invoked.
1028  */
1029 void af_alg_async_cb(struct crypto_async_request *_req, int err)
1030 {
1031 	struct af_alg_async_req *areq = _req->data;
1032 	struct sock *sk = areq->sk;
1033 	struct kiocb *iocb = areq->iocb;
1034 	unsigned int resultlen;
1035 
1036 	/* Buffer size written by crypto operation. */
1037 	resultlen = areq->outlen;
1038 
1039 	af_alg_free_resources(areq);
1040 	sock_put(sk);
1041 
1042 	iocb->ki_complete(iocb, err ? err : (int)resultlen, 0);
1043 }
1044 EXPORT_SYMBOL_GPL(af_alg_async_cb);
1045 
1046 /**
1047  * af_alg_poll - poll system call handler
1048  */
1049 __poll_t af_alg_poll(struct file *file, struct socket *sock,
1050 			 poll_table *wait)
1051 {
1052 	struct sock *sk = sock->sk;
1053 	struct alg_sock *ask = alg_sk(sk);
1054 	struct af_alg_ctx *ctx = ask->private;
1055 	__poll_t mask;
1056 
1057 	sock_poll_wait(file, sock, wait);
1058 	mask = 0;
1059 
1060 	if (!ctx->more || ctx->used)
1061 		mask |= EPOLLIN | EPOLLRDNORM;
1062 
1063 	if (af_alg_writable(sk))
1064 		mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
1065 
1066 	return mask;
1067 }
1068 EXPORT_SYMBOL_GPL(af_alg_poll);
1069 
1070 /**
1071  * af_alg_alloc_areq - allocate struct af_alg_async_req
1072  *
1073  * @sk socket of connection to user space
1074  * @areqlen size of struct af_alg_async_req + crypto_*_reqsize
1075  * @return allocated data structure or ERR_PTR upon error
1076  */
1077 struct af_alg_async_req *af_alg_alloc_areq(struct sock *sk,
1078 					   unsigned int areqlen)
1079 {
1080 	struct af_alg_async_req *areq = sock_kmalloc(sk, areqlen, GFP_KERNEL);
1081 
1082 	if (unlikely(!areq))
1083 		return ERR_PTR(-ENOMEM);
1084 
1085 	areq->areqlen = areqlen;
1086 	areq->sk = sk;
1087 	areq->last_rsgl = NULL;
1088 	INIT_LIST_HEAD(&areq->rsgl_list);
1089 	areq->tsgl = NULL;
1090 	areq->tsgl_entries = 0;
1091 
1092 	return areq;
1093 }
1094 EXPORT_SYMBOL_GPL(af_alg_alloc_areq);
1095 
1096 /**
1097  * af_alg_get_rsgl - create the RX SGL for the output data from the crypto
1098  *		     operation
1099  *
1100  * @sk socket of connection to user space
1101  * @msg user space message
1102  * @flags flags used to invoke recvmsg with
1103  * @areq instance of the cryptographic request that will hold the RX SGL
1104  * @maxsize maximum number of bytes to be pulled from user space
1105  * @outlen number of bytes in the RX SGL
1106  * @return 0 on success, < 0 upon error
1107  */
1108 int af_alg_get_rsgl(struct sock *sk, struct msghdr *msg, int flags,
1109 		    struct af_alg_async_req *areq, size_t maxsize,
1110 		    size_t *outlen)
1111 {
1112 	struct alg_sock *ask = alg_sk(sk);
1113 	struct af_alg_ctx *ctx = ask->private;
1114 	size_t len = 0;
1115 
1116 	while (maxsize > len && msg_data_left(msg)) {
1117 		struct af_alg_rsgl *rsgl;
1118 		size_t seglen;
1119 		int err;
1120 
1121 		/* limit the amount of readable buffers */
1122 		if (!af_alg_readable(sk))
1123 			break;
1124 
1125 		seglen = min_t(size_t, (maxsize - len),
1126 			       msg_data_left(msg));
1127 
1128 		if (list_empty(&areq->rsgl_list)) {
1129 			rsgl = &areq->first_rsgl;
1130 		} else {
1131 			rsgl = sock_kmalloc(sk, sizeof(*rsgl), GFP_KERNEL);
1132 			if (unlikely(!rsgl))
1133 				return -ENOMEM;
1134 		}
1135 
1136 		rsgl->sgl.npages = 0;
1137 		list_add_tail(&rsgl->list, &areq->rsgl_list);
1138 
1139 		/* make one iovec available as scatterlist */
1140 		err = af_alg_make_sg(&rsgl->sgl, &msg->msg_iter, seglen);
1141 		if (err < 0) {
1142 			rsgl->sg_num_bytes = 0;
1143 			return err;
1144 		}
1145 
1146 		/* chain the new scatterlist with previous one */
1147 		if (areq->last_rsgl)
1148 			af_alg_link_sg(&areq->last_rsgl->sgl, &rsgl->sgl);
1149 
1150 		areq->last_rsgl = rsgl;
1151 		len += err;
1152 		atomic_add(err, &ctx->rcvused);
1153 		rsgl->sg_num_bytes = err;
1154 		iov_iter_advance(&msg->msg_iter, err);
1155 	}
1156 
1157 	*outlen = len;
1158 	return 0;
1159 }
1160 EXPORT_SYMBOL_GPL(af_alg_get_rsgl);
1161 
1162 static int __init af_alg_init(void)
1163 {
1164 	int err = proto_register(&alg_proto, 0);
1165 
1166 	if (err)
1167 		goto out;
1168 
1169 	err = sock_register(&alg_family);
1170 	if (err != 0)
1171 		goto out_unregister_proto;
1172 
1173 out:
1174 	return err;
1175 
1176 out_unregister_proto:
1177 	proto_unregister(&alg_proto);
1178 	goto out;
1179 }
1180 
1181 static void __exit af_alg_exit(void)
1182 {
1183 	sock_unregister(PF_ALG);
1184 	proto_unregister(&alg_proto);
1185 }
1186 
1187 module_init(af_alg_init);
1188 module_exit(af_alg_exit);
1189 MODULE_LICENSE("GPL");
1190 MODULE_ALIAS_NETPROTO(AF_ALG);
1191