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