Mention branches and keyring.
[releases.git] / tls / tls_device.c
1 /* Copyright (c) 2018, Mellanox Technologies All rights reserved.
2  *
3  * This software is available to you under a choice of one of two
4  * licenses.  You may choose to be licensed under the terms of the GNU
5  * General Public License (GPL) Version 2, available from the file
6  * COPYING in the main directory of this source tree, or the
7  * OpenIB.org BSD license below:
8  *
9  *     Redistribution and use in source and binary forms, with or
10  *     without modification, are permitted provided that the following
11  *     conditions are met:
12  *
13  *      - Redistributions of source code must retain the above
14  *        copyright notice, this list of conditions and the following
15  *        disclaimer.
16  *
17  *      - Redistributions in binary form must reproduce the above
18  *        copyright notice, this list of conditions and the following
19  *        disclaimer in the documentation and/or other materials
20  *        provided with the distribution.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
26  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
27  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
28  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29  * SOFTWARE.
30  */
31
32 #include <crypto/aead.h>
33 #include <linux/highmem.h>
34 #include <linux/module.h>
35 #include <linux/netdevice.h>
36 #include <net/dst.h>
37 #include <net/inet_connection_sock.h>
38 #include <net/tcp.h>
39 #include <net/tls.h>
40
41 #include "tls.h"
42 #include "trace.h"
43
44 /* device_offload_lock is used to synchronize tls_dev_add
45  * against NETDEV_DOWN notifications.
46  */
47 static DECLARE_RWSEM(device_offload_lock);
48
49 static struct workqueue_struct *destruct_wq __read_mostly;
50
51 static LIST_HEAD(tls_device_list);
52 static LIST_HEAD(tls_device_down_list);
53 static DEFINE_SPINLOCK(tls_device_lock);
54
55 static struct page *dummy_page;
56
57 static void tls_device_free_ctx(struct tls_context *ctx)
58 {
59         if (ctx->tx_conf == TLS_HW) {
60                 kfree(tls_offload_ctx_tx(ctx));
61                 kfree(ctx->tx.rec_seq);
62                 kfree(ctx->tx.iv);
63         }
64
65         if (ctx->rx_conf == TLS_HW)
66                 kfree(tls_offload_ctx_rx(ctx));
67
68         tls_ctx_free(NULL, ctx);
69 }
70
71 static void tls_device_tx_del_task(struct work_struct *work)
72 {
73         struct tls_offload_context_tx *offload_ctx =
74                 container_of(work, struct tls_offload_context_tx, destruct_work);
75         struct tls_context *ctx = offload_ctx->ctx;
76         struct net_device *netdev;
77
78         /* Safe, because this is the destroy flow, refcount is 0, so
79          * tls_device_down can't store this field in parallel.
80          */
81         netdev = rcu_dereference_protected(ctx->netdev,
82                                            !refcount_read(&ctx->refcount));
83
84         netdev->tlsdev_ops->tls_dev_del(netdev, ctx, TLS_OFFLOAD_CTX_DIR_TX);
85         dev_put(netdev);
86         ctx->netdev = NULL;
87         tls_device_free_ctx(ctx);
88 }
89
90 static void tls_device_queue_ctx_destruction(struct tls_context *ctx)
91 {
92         struct net_device *netdev;
93         unsigned long flags;
94         bool async_cleanup;
95
96         spin_lock_irqsave(&tls_device_lock, flags);
97         if (unlikely(!refcount_dec_and_test(&ctx->refcount))) {
98                 spin_unlock_irqrestore(&tls_device_lock, flags);
99                 return;
100         }
101
102         list_del(&ctx->list); /* Remove from tls_device_list / tls_device_down_list */
103
104         /* Safe, because this is the destroy flow, refcount is 0, so
105          * tls_device_down can't store this field in parallel.
106          */
107         netdev = rcu_dereference_protected(ctx->netdev,
108                                            !refcount_read(&ctx->refcount));
109
110         async_cleanup = netdev && ctx->tx_conf == TLS_HW;
111         if (async_cleanup) {
112                 struct tls_offload_context_tx *offload_ctx = tls_offload_ctx_tx(ctx);
113
114                 /* queue_work inside the spinlock
115                  * to make sure tls_device_down waits for that work.
116                  */
117                 queue_work(destruct_wq, &offload_ctx->destruct_work);
118         }
119         spin_unlock_irqrestore(&tls_device_lock, flags);
120
121         if (!async_cleanup)
122                 tls_device_free_ctx(ctx);
123 }
124
125 /* We assume that the socket is already connected */
126 static struct net_device *get_netdev_for_sock(struct sock *sk)
127 {
128         struct dst_entry *dst = sk_dst_get(sk);
129         struct net_device *netdev = NULL;
130
131         if (likely(dst)) {
132                 netdev = netdev_sk_get_lowest_dev(dst->dev, sk);
133                 dev_hold(netdev);
134         }
135
136         dst_release(dst);
137
138         return netdev;
139 }
140
141 static void destroy_record(struct tls_record_info *record)
142 {
143         int i;
144
145         for (i = 0; i < record->num_frags; i++)
146                 __skb_frag_unref(&record->frags[i], false);
147         kfree(record);
148 }
149
150 static void delete_all_records(struct tls_offload_context_tx *offload_ctx)
151 {
152         struct tls_record_info *info, *temp;
153
154         list_for_each_entry_safe(info, temp, &offload_ctx->records_list, list) {
155                 list_del(&info->list);
156                 destroy_record(info);
157         }
158
159         offload_ctx->retransmit_hint = NULL;
160 }
161
162 static void tls_icsk_clean_acked(struct sock *sk, u32 acked_seq)
163 {
164         struct tls_context *tls_ctx = tls_get_ctx(sk);
165         struct tls_record_info *info, *temp;
166         struct tls_offload_context_tx *ctx;
167         u64 deleted_records = 0;
168         unsigned long flags;
169
170         if (!tls_ctx)
171                 return;
172
173         ctx = tls_offload_ctx_tx(tls_ctx);
174
175         spin_lock_irqsave(&ctx->lock, flags);
176         info = ctx->retransmit_hint;
177         if (info && !before(acked_seq, info->end_seq))
178                 ctx->retransmit_hint = NULL;
179
180         list_for_each_entry_safe(info, temp, &ctx->records_list, list) {
181                 if (before(acked_seq, info->end_seq))
182                         break;
183                 list_del(&info->list);
184
185                 destroy_record(info);
186                 deleted_records++;
187         }
188
189         ctx->unacked_record_sn += deleted_records;
190         spin_unlock_irqrestore(&ctx->lock, flags);
191 }
192
193 /* At this point, there should be no references on this
194  * socket and no in-flight SKBs associated with this
195  * socket, so it is safe to free all the resources.
196  */
197 void tls_device_sk_destruct(struct sock *sk)
198 {
199         struct tls_context *tls_ctx = tls_get_ctx(sk);
200         struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
201
202         tls_ctx->sk_destruct(sk);
203
204         if (tls_ctx->tx_conf == TLS_HW) {
205                 if (ctx->open_record)
206                         destroy_record(ctx->open_record);
207                 delete_all_records(ctx);
208                 crypto_free_aead(ctx->aead_send);
209                 clean_acked_data_disable(inet_csk(sk));
210         }
211
212         tls_device_queue_ctx_destruction(tls_ctx);
213 }
214 EXPORT_SYMBOL_GPL(tls_device_sk_destruct);
215
216 void tls_device_free_resources_tx(struct sock *sk)
217 {
218         struct tls_context *tls_ctx = tls_get_ctx(sk);
219
220         tls_free_partial_record(sk, tls_ctx);
221 }
222
223 void tls_offload_tx_resync_request(struct sock *sk, u32 got_seq, u32 exp_seq)
224 {
225         struct tls_context *tls_ctx = tls_get_ctx(sk);
226
227         trace_tls_device_tx_resync_req(sk, got_seq, exp_seq);
228         WARN_ON(test_and_set_bit(TLS_TX_SYNC_SCHED, &tls_ctx->flags));
229 }
230 EXPORT_SYMBOL_GPL(tls_offload_tx_resync_request);
231
232 static void tls_device_resync_tx(struct sock *sk, struct tls_context *tls_ctx,
233                                  u32 seq)
234 {
235         struct net_device *netdev;
236         struct sk_buff *skb;
237         int err = 0;
238         u8 *rcd_sn;
239
240         skb = tcp_write_queue_tail(sk);
241         if (skb)
242                 TCP_SKB_CB(skb)->eor = 1;
243
244         rcd_sn = tls_ctx->tx.rec_seq;
245
246         trace_tls_device_tx_resync_send(sk, seq, rcd_sn);
247         down_read(&device_offload_lock);
248         netdev = rcu_dereference_protected(tls_ctx->netdev,
249                                            lockdep_is_held(&device_offload_lock));
250         if (netdev)
251                 err = netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq,
252                                                          rcd_sn,
253                                                          TLS_OFFLOAD_CTX_DIR_TX);
254         up_read(&device_offload_lock);
255         if (err)
256                 return;
257
258         clear_bit_unlock(TLS_TX_SYNC_SCHED, &tls_ctx->flags);
259 }
260
261 static void tls_append_frag(struct tls_record_info *record,
262                             struct page_frag *pfrag,
263                             int size)
264 {
265         skb_frag_t *frag;
266
267         frag = &record->frags[record->num_frags - 1];
268         if (skb_frag_page(frag) == pfrag->page &&
269             skb_frag_off(frag) + skb_frag_size(frag) == pfrag->offset) {
270                 skb_frag_size_add(frag, size);
271         } else {
272                 ++frag;
273                 __skb_frag_set_page(frag, pfrag->page);
274                 skb_frag_off_set(frag, pfrag->offset);
275                 skb_frag_size_set(frag, size);
276                 ++record->num_frags;
277                 get_page(pfrag->page);
278         }
279
280         pfrag->offset += size;
281         record->len += size;
282 }
283
284 static int tls_push_record(struct sock *sk,
285                            struct tls_context *ctx,
286                            struct tls_offload_context_tx *offload_ctx,
287                            struct tls_record_info *record,
288                            int flags)
289 {
290         struct tls_prot_info *prot = &ctx->prot_info;
291         struct tcp_sock *tp = tcp_sk(sk);
292         skb_frag_t *frag;
293         int i;
294
295         record->end_seq = tp->write_seq + record->len;
296         list_add_tail_rcu(&record->list, &offload_ctx->records_list);
297         offload_ctx->open_record = NULL;
298
299         if (test_bit(TLS_TX_SYNC_SCHED, &ctx->flags))
300                 tls_device_resync_tx(sk, ctx, tp->write_seq);
301
302         tls_advance_record_sn(sk, prot, &ctx->tx);
303
304         for (i = 0; i < record->num_frags; i++) {
305                 frag = &record->frags[i];
306                 sg_unmark_end(&offload_ctx->sg_tx_data[i]);
307                 sg_set_page(&offload_ctx->sg_tx_data[i], skb_frag_page(frag),
308                             skb_frag_size(frag), skb_frag_off(frag));
309                 sk_mem_charge(sk, skb_frag_size(frag));
310                 get_page(skb_frag_page(frag));
311         }
312         sg_mark_end(&offload_ctx->sg_tx_data[record->num_frags - 1]);
313
314         /* all ready, send */
315         return tls_push_sg(sk, ctx, offload_ctx->sg_tx_data, 0, flags);
316 }
317
318 static void tls_device_record_close(struct sock *sk,
319                                     struct tls_context *ctx,
320                                     struct tls_record_info *record,
321                                     struct page_frag *pfrag,
322                                     unsigned char record_type)
323 {
324         struct tls_prot_info *prot = &ctx->prot_info;
325         struct page_frag dummy_tag_frag;
326
327         /* append tag
328          * device will fill in the tag, we just need to append a placeholder
329          * use socket memory to improve coalescing (re-using a single buffer
330          * increases frag count)
331          * if we can't allocate memory now use the dummy page
332          */
333         if (unlikely(pfrag->size - pfrag->offset < prot->tag_size) &&
334             !skb_page_frag_refill(prot->tag_size, pfrag, sk->sk_allocation)) {
335                 dummy_tag_frag.page = dummy_page;
336                 dummy_tag_frag.offset = 0;
337                 pfrag = &dummy_tag_frag;
338         }
339         tls_append_frag(record, pfrag, prot->tag_size);
340
341         /* fill prepend */
342         tls_fill_prepend(ctx, skb_frag_address(&record->frags[0]),
343                          record->len - prot->overhead_size,
344                          record_type);
345 }
346
347 static int tls_create_new_record(struct tls_offload_context_tx *offload_ctx,
348                                  struct page_frag *pfrag,
349                                  size_t prepend_size)
350 {
351         struct tls_record_info *record;
352         skb_frag_t *frag;
353
354         record = kmalloc(sizeof(*record), GFP_KERNEL);
355         if (!record)
356                 return -ENOMEM;
357
358         frag = &record->frags[0];
359         __skb_frag_set_page(frag, pfrag->page);
360         skb_frag_off_set(frag, pfrag->offset);
361         skb_frag_size_set(frag, prepend_size);
362
363         get_page(pfrag->page);
364         pfrag->offset += prepend_size;
365
366         record->num_frags = 1;
367         record->len = prepend_size;
368         offload_ctx->open_record = record;
369         return 0;
370 }
371
372 static int tls_do_allocation(struct sock *sk,
373                              struct tls_offload_context_tx *offload_ctx,
374                              struct page_frag *pfrag,
375                              size_t prepend_size)
376 {
377         int ret;
378
379         if (!offload_ctx->open_record) {
380                 if (unlikely(!skb_page_frag_refill(prepend_size, pfrag,
381                                                    sk->sk_allocation))) {
382                         READ_ONCE(sk->sk_prot)->enter_memory_pressure(sk);
383                         sk_stream_moderate_sndbuf(sk);
384                         return -ENOMEM;
385                 }
386
387                 ret = tls_create_new_record(offload_ctx, pfrag, prepend_size);
388                 if (ret)
389                         return ret;
390
391                 if (pfrag->size > pfrag->offset)
392                         return 0;
393         }
394
395         if (!sk_page_frag_refill(sk, pfrag))
396                 return -ENOMEM;
397
398         return 0;
399 }
400
401 static int tls_device_copy_data(void *addr, size_t bytes, struct iov_iter *i)
402 {
403         size_t pre_copy, nocache;
404
405         pre_copy = ~((unsigned long)addr - 1) & (SMP_CACHE_BYTES - 1);
406         if (pre_copy) {
407                 pre_copy = min(pre_copy, bytes);
408                 if (copy_from_iter(addr, pre_copy, i) != pre_copy)
409                         return -EFAULT;
410                 bytes -= pre_copy;
411                 addr += pre_copy;
412         }
413
414         nocache = round_down(bytes, SMP_CACHE_BYTES);
415         if (copy_from_iter_nocache(addr, nocache, i) != nocache)
416                 return -EFAULT;
417         bytes -= nocache;
418         addr += nocache;
419
420         if (bytes && copy_from_iter(addr, bytes, i) != bytes)
421                 return -EFAULT;
422
423         return 0;
424 }
425
426 union tls_iter_offset {
427         struct iov_iter *msg_iter;
428         int offset;
429 };
430
431 static int tls_push_data(struct sock *sk,
432                          union tls_iter_offset iter_offset,
433                          size_t size, int flags,
434                          unsigned char record_type,
435                          struct page *zc_page)
436 {
437         struct tls_context *tls_ctx = tls_get_ctx(sk);
438         struct tls_prot_info *prot = &tls_ctx->prot_info;
439         struct tls_offload_context_tx *ctx = tls_offload_ctx_tx(tls_ctx);
440         struct tls_record_info *record;
441         int tls_push_record_flags;
442         struct page_frag *pfrag;
443         size_t orig_size = size;
444         u32 max_open_record_len;
445         bool more = false;
446         bool done = false;
447         int copy, rc = 0;
448         long timeo;
449
450         if (flags &
451             ~(MSG_MORE | MSG_DONTWAIT | MSG_NOSIGNAL | MSG_SENDPAGE_NOTLAST))
452                 return -EOPNOTSUPP;
453
454         if (unlikely(sk->sk_err))
455                 return -sk->sk_err;
456
457         flags |= MSG_SENDPAGE_DECRYPTED;
458         tls_push_record_flags = flags | MSG_SENDPAGE_NOTLAST;
459
460         timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT);
461         if (tls_is_partially_sent_record(tls_ctx)) {
462                 rc = tls_push_partial_record(sk, tls_ctx, flags);
463                 if (rc < 0)
464                         return rc;
465         }
466
467         pfrag = sk_page_frag(sk);
468
469         /* TLS_HEADER_SIZE is not counted as part of the TLS record, and
470          * we need to leave room for an authentication tag.
471          */
472         max_open_record_len = TLS_MAX_PAYLOAD_SIZE +
473                               prot->prepend_size;
474         do {
475                 rc = tls_do_allocation(sk, ctx, pfrag, prot->prepend_size);
476                 if (unlikely(rc)) {
477                         rc = sk_stream_wait_memory(sk, &timeo);
478                         if (!rc)
479                                 continue;
480
481                         record = ctx->open_record;
482                         if (!record)
483                                 break;
484 handle_error:
485                         if (record_type != TLS_RECORD_TYPE_DATA) {
486                                 /* avoid sending partial
487                                  * record with type !=
488                                  * application_data
489                                  */
490                                 size = orig_size;
491                                 destroy_record(record);
492                                 ctx->open_record = NULL;
493                         } else if (record->len > prot->prepend_size) {
494                                 goto last_record;
495                         }
496
497                         break;
498                 }
499
500                 record = ctx->open_record;
501
502                 copy = min_t(size_t, size, max_open_record_len - record->len);
503                 if (copy && zc_page) {
504                         struct page_frag zc_pfrag;
505
506                         zc_pfrag.page = zc_page;
507                         zc_pfrag.offset = iter_offset.offset;
508                         zc_pfrag.size = copy;
509                         tls_append_frag(record, &zc_pfrag, copy);
510
511                         iter_offset.offset += copy;
512                 } else if (copy) {
513                         copy = min_t(size_t, copy, pfrag->size - pfrag->offset);
514
515                         rc = tls_device_copy_data(page_address(pfrag->page) +
516                                                   pfrag->offset, copy,
517                                                   iter_offset.msg_iter);
518                         if (rc)
519                                 goto handle_error;
520                         tls_append_frag(record, pfrag, copy);
521                 }
522
523                 size -= copy;
524                 if (!size) {
525 last_record:
526                         tls_push_record_flags = flags;
527                         if (flags & (MSG_SENDPAGE_NOTLAST | MSG_MORE)) {
528                                 more = true;
529                                 break;
530                         }
531
532                         done = true;
533                 }
534
535                 if (done || record->len >= max_open_record_len ||
536                     (record->num_frags >= MAX_SKB_FRAGS - 1)) {
537                         tls_device_record_close(sk, tls_ctx, record,
538                                                 pfrag, record_type);
539
540                         rc = tls_push_record(sk,
541                                              tls_ctx,
542                                              ctx,
543                                              record,
544                                              tls_push_record_flags);
545                         if (rc < 0)
546                                 break;
547                 }
548         } while (!done);
549
550         tls_ctx->pending_open_record_frags = more;
551
552         if (orig_size - size > 0)
553                 rc = orig_size - size;
554
555         return rc;
556 }
557
558 int tls_device_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
559 {
560         unsigned char record_type = TLS_RECORD_TYPE_DATA;
561         struct tls_context *tls_ctx = tls_get_ctx(sk);
562         union tls_iter_offset iter;
563         int rc;
564
565         mutex_lock(&tls_ctx->tx_lock);
566         lock_sock(sk);
567
568         if (unlikely(msg->msg_controllen)) {
569                 rc = tls_process_cmsg(sk, msg, &record_type);
570                 if (rc)
571                         goto out;
572         }
573
574         iter.msg_iter = &msg->msg_iter;
575         rc = tls_push_data(sk, iter, size, msg->msg_flags, record_type, NULL);
576
577 out:
578         release_sock(sk);
579         mutex_unlock(&tls_ctx->tx_lock);
580         return rc;
581 }
582
583 int tls_device_sendpage(struct sock *sk, struct page *page,
584                         int offset, size_t size, int flags)
585 {
586         struct tls_context *tls_ctx = tls_get_ctx(sk);
587         union tls_iter_offset iter_offset;
588         struct iov_iter msg_iter;
589         char *kaddr;
590         struct kvec iov;
591         int rc;
592
593         if (flags & MSG_SENDPAGE_NOTLAST)
594                 flags |= MSG_MORE;
595
596         mutex_lock(&tls_ctx->tx_lock);
597         lock_sock(sk);
598
599         if (flags & MSG_OOB) {
600                 rc = -EOPNOTSUPP;
601                 goto out;
602         }
603
604         if (tls_ctx->zerocopy_sendfile) {
605                 iter_offset.offset = offset;
606                 rc = tls_push_data(sk, iter_offset, size,
607                                    flags, TLS_RECORD_TYPE_DATA, page);
608                 goto out;
609         }
610
611         kaddr = kmap(page);
612         iov.iov_base = kaddr + offset;
613         iov.iov_len = size;
614         iov_iter_kvec(&msg_iter, ITER_SOURCE, &iov, 1, size);
615         iter_offset.msg_iter = &msg_iter;
616         rc = tls_push_data(sk, iter_offset, size, flags, TLS_RECORD_TYPE_DATA,
617                            NULL);
618         kunmap(page);
619
620 out:
621         release_sock(sk);
622         mutex_unlock(&tls_ctx->tx_lock);
623         return rc;
624 }
625
626 struct tls_record_info *tls_get_record(struct tls_offload_context_tx *context,
627                                        u32 seq, u64 *p_record_sn)
628 {
629         u64 record_sn = context->hint_record_sn;
630         struct tls_record_info *info, *last;
631
632         info = context->retransmit_hint;
633         if (!info ||
634             before(seq, info->end_seq - info->len)) {
635                 /* if retransmit_hint is irrelevant start
636                  * from the beginning of the list
637                  */
638                 info = list_first_entry_or_null(&context->records_list,
639                                                 struct tls_record_info, list);
640                 if (!info)
641                         return NULL;
642                 /* send the start_marker record if seq number is before the
643                  * tls offload start marker sequence number. This record is
644                  * required to handle TCP packets which are before TLS offload
645                  * started.
646                  *  And if it's not start marker, look if this seq number
647                  * belongs to the list.
648                  */
649                 if (likely(!tls_record_is_start_marker(info))) {
650                         /* we have the first record, get the last record to see
651                          * if this seq number belongs to the list.
652                          */
653                         last = list_last_entry(&context->records_list,
654                                                struct tls_record_info, list);
655
656                         if (!between(seq, tls_record_start_seq(info),
657                                      last->end_seq))
658                                 return NULL;
659                 }
660                 record_sn = context->unacked_record_sn;
661         }
662
663         /* We just need the _rcu for the READ_ONCE() */
664         rcu_read_lock();
665         list_for_each_entry_from_rcu(info, &context->records_list, list) {
666                 if (before(seq, info->end_seq)) {
667                         if (!context->retransmit_hint ||
668                             after(info->end_seq,
669                                   context->retransmit_hint->end_seq)) {
670                                 context->hint_record_sn = record_sn;
671                                 context->retransmit_hint = info;
672                         }
673                         *p_record_sn = record_sn;
674                         goto exit_rcu_unlock;
675                 }
676                 record_sn++;
677         }
678         info = NULL;
679
680 exit_rcu_unlock:
681         rcu_read_unlock();
682         return info;
683 }
684 EXPORT_SYMBOL(tls_get_record);
685
686 static int tls_device_push_pending_record(struct sock *sk, int flags)
687 {
688         union tls_iter_offset iter;
689         struct iov_iter msg_iter;
690
691         iov_iter_kvec(&msg_iter, ITER_SOURCE, NULL, 0, 0);
692         iter.msg_iter = &msg_iter;
693         return tls_push_data(sk, iter, 0, flags, TLS_RECORD_TYPE_DATA, NULL);
694 }
695
696 void tls_device_write_space(struct sock *sk, struct tls_context *ctx)
697 {
698         if (tls_is_partially_sent_record(ctx)) {
699                 gfp_t sk_allocation = sk->sk_allocation;
700
701                 WARN_ON_ONCE(sk->sk_write_pending);
702
703                 sk->sk_allocation = GFP_ATOMIC;
704                 tls_push_partial_record(sk, ctx,
705                                         MSG_DONTWAIT | MSG_NOSIGNAL |
706                                         MSG_SENDPAGE_DECRYPTED);
707                 sk->sk_allocation = sk_allocation;
708         }
709 }
710
711 static void tls_device_resync_rx(struct tls_context *tls_ctx,
712                                  struct sock *sk, u32 seq, u8 *rcd_sn)
713 {
714         struct tls_offload_context_rx *rx_ctx = tls_offload_ctx_rx(tls_ctx);
715         struct net_device *netdev;
716
717         trace_tls_device_rx_resync_send(sk, seq, rcd_sn, rx_ctx->resync_type);
718         rcu_read_lock();
719         netdev = rcu_dereference(tls_ctx->netdev);
720         if (netdev)
721                 netdev->tlsdev_ops->tls_dev_resync(netdev, sk, seq, rcd_sn,
722                                                    TLS_OFFLOAD_CTX_DIR_RX);
723         rcu_read_unlock();
724         TLS_INC_STATS(sock_net(sk), LINUX_MIB_TLSRXDEVICERESYNC);
725 }
726
727 static bool
728 tls_device_rx_resync_async(struct tls_offload_resync_async *resync_async,
729                            s64 resync_req, u32 *seq, u16 *rcd_delta)
730 {
731         u32 is_async = resync_req & RESYNC_REQ_ASYNC;
732         u32 req_seq = resync_req >> 32;
733         u32 req_end = req_seq + ((resync_req >> 16) & 0xffff);
734         u16 i;
735
736         *rcd_delta = 0;
737
738         if (is_async) {
739                 /* shouldn't get to wraparound:
740                  * too long in async stage, something bad happened
741                  */
742                 if (WARN_ON_ONCE(resync_async->rcd_delta == USHRT_MAX))
743                         return false;
744
745                 /* asynchronous stage: log all headers seq such that
746                  * req_seq <= seq <= end_seq, and wait for real resync request
747                  */
748                 if (before(*seq, req_seq))
749                         return false;
750                 if (!after(*seq, req_end) &&
751                     resync_async->loglen < TLS_DEVICE_RESYNC_ASYNC_LOGMAX)
752                         resync_async->log[resync_async->loglen++] = *seq;
753
754                 resync_async->rcd_delta++;
755
756                 return false;
757         }
758
759         /* synchronous stage: check against the logged entries and
760          * proceed to check the next entries if no match was found
761          */
762         for (i = 0; i < resync_async->loglen; i++)
763                 if (req_seq == resync_async->log[i] &&
764                     atomic64_try_cmpxchg(&resync_async->req, &resync_req, 0)) {
765                         *rcd_delta = resync_async->rcd_delta - i;
766                         *seq = req_seq;
767                         resync_async->loglen = 0;
768                         resync_async->rcd_delta = 0;
769                         return true;
770                 }
771
772         resync_async->loglen = 0;
773         resync_async->rcd_delta = 0;
774
775         if (req_seq == *seq &&
776             atomic64_try_cmpxchg(&resync_async->req,
777                                  &resync_req, 0))
778                 return true;
779
780         return false;
781 }
782
783 void tls_device_rx_resync_new_rec(struct sock *sk, u32 rcd_len, u32 seq)
784 {
785         struct tls_context *tls_ctx = tls_get_ctx(sk);
786         struct tls_offload_context_rx *rx_ctx;
787         u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
788         u32 sock_data, is_req_pending;
789         struct tls_prot_info *prot;
790         s64 resync_req;
791         u16 rcd_delta;
792         u32 req_seq;
793
794         if (tls_ctx->rx_conf != TLS_HW)
795                 return;
796         if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags)))
797                 return;
798
799         prot = &tls_ctx->prot_info;
800         rx_ctx = tls_offload_ctx_rx(tls_ctx);
801         memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
802
803         switch (rx_ctx->resync_type) {
804         case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ:
805                 resync_req = atomic64_read(&rx_ctx->resync_req);
806                 req_seq = resync_req >> 32;
807                 seq += TLS_HEADER_SIZE - 1;
808                 is_req_pending = resync_req;
809
810                 if (likely(!is_req_pending) || req_seq != seq ||
811                     !atomic64_try_cmpxchg(&rx_ctx->resync_req, &resync_req, 0))
812                         return;
813                 break;
814         case TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT:
815                 if (likely(!rx_ctx->resync_nh_do_now))
816                         return;
817
818                 /* head of next rec is already in, note that the sock_inq will
819                  * include the currently parsed message when called from parser
820                  */
821                 sock_data = tcp_inq(sk);
822                 if (sock_data > rcd_len) {
823                         trace_tls_device_rx_resync_nh_delay(sk, sock_data,
824                                                             rcd_len);
825                         return;
826                 }
827
828                 rx_ctx->resync_nh_do_now = 0;
829                 seq += rcd_len;
830                 tls_bigint_increment(rcd_sn, prot->rec_seq_size);
831                 break;
832         case TLS_OFFLOAD_SYNC_TYPE_DRIVER_REQ_ASYNC:
833                 resync_req = atomic64_read(&rx_ctx->resync_async->req);
834                 is_req_pending = resync_req;
835                 if (likely(!is_req_pending))
836                         return;
837
838                 if (!tls_device_rx_resync_async(rx_ctx->resync_async,
839                                                 resync_req, &seq, &rcd_delta))
840                         return;
841                 tls_bigint_subtract(rcd_sn, rcd_delta);
842                 break;
843         }
844
845         tls_device_resync_rx(tls_ctx, sk, seq, rcd_sn);
846 }
847
848 static void tls_device_core_ctrl_rx_resync(struct tls_context *tls_ctx,
849                                            struct tls_offload_context_rx *ctx,
850                                            struct sock *sk, struct sk_buff *skb)
851 {
852         struct strp_msg *rxm;
853
854         /* device will request resyncs by itself based on stream scan */
855         if (ctx->resync_type != TLS_OFFLOAD_SYNC_TYPE_CORE_NEXT_HINT)
856                 return;
857         /* already scheduled */
858         if (ctx->resync_nh_do_now)
859                 return;
860         /* seen decrypted fragments since last fully-failed record */
861         if (ctx->resync_nh_reset) {
862                 ctx->resync_nh_reset = 0;
863                 ctx->resync_nh.decrypted_failed = 1;
864                 ctx->resync_nh.decrypted_tgt = TLS_DEVICE_RESYNC_NH_START_IVAL;
865                 return;
866         }
867
868         if (++ctx->resync_nh.decrypted_failed <= ctx->resync_nh.decrypted_tgt)
869                 return;
870
871         /* doing resync, bump the next target in case it fails */
872         if (ctx->resync_nh.decrypted_tgt < TLS_DEVICE_RESYNC_NH_MAX_IVAL)
873                 ctx->resync_nh.decrypted_tgt *= 2;
874         else
875                 ctx->resync_nh.decrypted_tgt += TLS_DEVICE_RESYNC_NH_MAX_IVAL;
876
877         rxm = strp_msg(skb);
878
879         /* head of next rec is already in, parser will sync for us */
880         if (tcp_inq(sk) > rxm->full_len) {
881                 trace_tls_device_rx_resync_nh_schedule(sk);
882                 ctx->resync_nh_do_now = 1;
883         } else {
884                 struct tls_prot_info *prot = &tls_ctx->prot_info;
885                 u8 rcd_sn[TLS_MAX_REC_SEQ_SIZE];
886
887                 memcpy(rcd_sn, tls_ctx->rx.rec_seq, prot->rec_seq_size);
888                 tls_bigint_increment(rcd_sn, prot->rec_seq_size);
889
890                 tls_device_resync_rx(tls_ctx, sk, tcp_sk(sk)->copied_seq,
891                                      rcd_sn);
892         }
893 }
894
895 static int
896 tls_device_reencrypt(struct sock *sk, struct tls_context *tls_ctx)
897 {
898         struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
899         const struct tls_cipher_size_desc *cipher_sz;
900         int err, offset, copy, data_len, pos;
901         struct sk_buff *skb, *skb_iter;
902         struct scatterlist sg[1];
903         struct strp_msg *rxm;
904         char *orig_buf, *buf;
905
906         switch (tls_ctx->crypto_recv.info.cipher_type) {
907         case TLS_CIPHER_AES_GCM_128:
908         case TLS_CIPHER_AES_GCM_256:
909                 break;
910         default:
911                 return -EINVAL;
912         }
913         cipher_sz = &tls_cipher_size_desc[tls_ctx->crypto_recv.info.cipher_type];
914
915         rxm = strp_msg(tls_strp_msg(sw_ctx));
916         orig_buf = kmalloc(rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv,
917                            sk->sk_allocation);
918         if (!orig_buf)
919                 return -ENOMEM;
920         buf = orig_buf;
921
922         err = tls_strp_msg_cow(sw_ctx);
923         if (unlikely(err))
924                 goto free_buf;
925
926         skb = tls_strp_msg(sw_ctx);
927         rxm = strp_msg(skb);
928         offset = rxm->offset;
929
930         sg_init_table(sg, 1);
931         sg_set_buf(&sg[0], buf,
932                    rxm->full_len + TLS_HEADER_SIZE + cipher_sz->iv);
933         err = skb_copy_bits(skb, offset, buf, TLS_HEADER_SIZE + cipher_sz->iv);
934         if (err)
935                 goto free_buf;
936
937         /* We are interested only in the decrypted data not the auth */
938         err = decrypt_skb(sk, sg);
939         if (err != -EBADMSG)
940                 goto free_buf;
941         else
942                 err = 0;
943
944         data_len = rxm->full_len - cipher_sz->tag;
945
946         if (skb_pagelen(skb) > offset) {
947                 copy = min_t(int, skb_pagelen(skb) - offset, data_len);
948
949                 if (skb->decrypted) {
950                         err = skb_store_bits(skb, offset, buf, copy);
951                         if (err)
952                                 goto free_buf;
953                 }
954
955                 offset += copy;
956                 buf += copy;
957         }
958
959         pos = skb_pagelen(skb);
960         skb_walk_frags(skb, skb_iter) {
961                 int frag_pos;
962
963                 /* Practically all frags must belong to msg if reencrypt
964                  * is needed with current strparser and coalescing logic,
965                  * but strparser may "get optimized", so let's be safe.
966                  */
967                 if (pos + skb_iter->len <= offset)
968                         goto done_with_frag;
969                 if (pos >= data_len + rxm->offset)
970                         break;
971
972                 frag_pos = offset - pos;
973                 copy = min_t(int, skb_iter->len - frag_pos,
974                              data_len + rxm->offset - offset);
975
976                 if (skb_iter->decrypted) {
977                         err = skb_store_bits(skb_iter, frag_pos, buf, copy);
978                         if (err)
979                                 goto free_buf;
980                 }
981
982                 offset += copy;
983                 buf += copy;
984 done_with_frag:
985                 pos += skb_iter->len;
986         }
987
988 free_buf:
989         kfree(orig_buf);
990         return err;
991 }
992
993 int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx)
994 {
995         struct tls_offload_context_rx *ctx = tls_offload_ctx_rx(tls_ctx);
996         struct tls_sw_context_rx *sw_ctx = tls_sw_ctx_rx(tls_ctx);
997         struct sk_buff *skb = tls_strp_msg(sw_ctx);
998         struct strp_msg *rxm = strp_msg(skb);
999         int is_decrypted, is_encrypted;
1000
1001         if (!tls_strp_msg_mixed_decrypted(sw_ctx)) {
1002                 is_decrypted = skb->decrypted;
1003                 is_encrypted = !is_decrypted;
1004         } else {
1005                 is_decrypted = 0;
1006                 is_encrypted = 0;
1007         }
1008
1009         trace_tls_device_decrypted(sk, tcp_sk(sk)->copied_seq - rxm->full_len,
1010                                    tls_ctx->rx.rec_seq, rxm->full_len,
1011                                    is_encrypted, is_decrypted);
1012
1013         if (unlikely(test_bit(TLS_RX_DEV_DEGRADED, &tls_ctx->flags))) {
1014                 if (likely(is_encrypted || is_decrypted))
1015                         return is_decrypted;
1016
1017                 /* After tls_device_down disables the offload, the next SKB will
1018                  * likely have initial fragments decrypted, and final ones not
1019                  * decrypted. We need to reencrypt that single SKB.
1020                  */
1021                 return tls_device_reencrypt(sk, tls_ctx);
1022         }
1023
1024         /* Return immediately if the record is either entirely plaintext or
1025          * entirely ciphertext. Otherwise handle reencrypt partially decrypted
1026          * record.
1027          */
1028         if (is_decrypted) {
1029                 ctx->resync_nh_reset = 1;
1030                 return is_decrypted;
1031         }
1032         if (is_encrypted) {
1033                 tls_device_core_ctrl_rx_resync(tls_ctx, ctx, sk, skb);
1034                 return 0;
1035         }
1036
1037         ctx->resync_nh_reset = 1;
1038         return tls_device_reencrypt(sk, tls_ctx);
1039 }
1040
1041 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
1042                               struct net_device *netdev)
1043 {
1044         if (sk->sk_destruct != tls_device_sk_destruct) {
1045                 refcount_set(&ctx->refcount, 1);
1046                 dev_hold(netdev);
1047                 RCU_INIT_POINTER(ctx->netdev, netdev);
1048                 spin_lock_irq(&tls_device_lock);
1049                 list_add_tail(&ctx->list, &tls_device_list);
1050                 spin_unlock_irq(&tls_device_lock);
1051
1052                 ctx->sk_destruct = sk->sk_destruct;
1053                 smp_store_release(&sk->sk_destruct, tls_device_sk_destruct);
1054         }
1055 }
1056
1057 int tls_set_device_offload(struct sock *sk, struct tls_context *ctx)
1058 {
1059         struct tls_context *tls_ctx = tls_get_ctx(sk);
1060         struct tls_prot_info *prot = &tls_ctx->prot_info;
1061         const struct tls_cipher_size_desc *cipher_sz;
1062         struct tls_record_info *start_marker_record;
1063         struct tls_offload_context_tx *offload_ctx;
1064         struct tls_crypto_info *crypto_info;
1065         struct net_device *netdev;
1066         char *iv, *rec_seq;
1067         struct sk_buff *skb;
1068         __be64 rcd_sn;
1069         int rc;
1070
1071         if (!ctx)
1072                 return -EINVAL;
1073
1074         if (ctx->priv_ctx_tx)
1075                 return -EEXIST;
1076
1077         netdev = get_netdev_for_sock(sk);
1078         if (!netdev) {
1079                 pr_err_ratelimited("%s: netdev not found\n", __func__);
1080                 return -EINVAL;
1081         }
1082
1083         if (!(netdev->features & NETIF_F_HW_TLS_TX)) {
1084                 rc = -EOPNOTSUPP;
1085                 goto release_netdev;
1086         }
1087
1088         crypto_info = &ctx->crypto_send.info;
1089         if (crypto_info->version != TLS_1_2_VERSION) {
1090                 rc = -EOPNOTSUPP;
1091                 goto release_netdev;
1092         }
1093
1094         switch (crypto_info->cipher_type) {
1095         case TLS_CIPHER_AES_GCM_128:
1096                 iv = ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->iv;
1097                 rec_seq =
1098                  ((struct tls12_crypto_info_aes_gcm_128 *)crypto_info)->rec_seq;
1099                 break;
1100         case TLS_CIPHER_AES_GCM_256:
1101                 iv = ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->iv;
1102                 rec_seq =
1103                  ((struct tls12_crypto_info_aes_gcm_256 *)crypto_info)->rec_seq;
1104                 break;
1105         default:
1106                 rc = -EINVAL;
1107                 goto release_netdev;
1108         }
1109         cipher_sz = &tls_cipher_size_desc[crypto_info->cipher_type];
1110
1111         /* Sanity-check the rec_seq_size for stack allocations */
1112         if (cipher_sz->rec_seq > TLS_MAX_REC_SEQ_SIZE) {
1113                 rc = -EINVAL;
1114                 goto release_netdev;
1115         }
1116
1117         prot->version = crypto_info->version;
1118         prot->cipher_type = crypto_info->cipher_type;
1119         prot->prepend_size = TLS_HEADER_SIZE + cipher_sz->iv;
1120         prot->tag_size = cipher_sz->tag;
1121         prot->overhead_size = prot->prepend_size + prot->tag_size;
1122         prot->iv_size = cipher_sz->iv;
1123         prot->salt_size = cipher_sz->salt;
1124         ctx->tx.iv = kmalloc(cipher_sz->iv + cipher_sz->salt, GFP_KERNEL);
1125         if (!ctx->tx.iv) {
1126                 rc = -ENOMEM;
1127                 goto release_netdev;
1128         }
1129
1130         memcpy(ctx->tx.iv + cipher_sz->salt, iv, cipher_sz->iv);
1131
1132         prot->rec_seq_size = cipher_sz->rec_seq;
1133         ctx->tx.rec_seq = kmemdup(rec_seq, cipher_sz->rec_seq, GFP_KERNEL);
1134         if (!ctx->tx.rec_seq) {
1135                 rc = -ENOMEM;
1136                 goto free_iv;
1137         }
1138
1139         start_marker_record = kmalloc(sizeof(*start_marker_record), GFP_KERNEL);
1140         if (!start_marker_record) {
1141                 rc = -ENOMEM;
1142                 goto free_rec_seq;
1143         }
1144
1145         offload_ctx = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_TX, GFP_KERNEL);
1146         if (!offload_ctx) {
1147                 rc = -ENOMEM;
1148                 goto free_marker_record;
1149         }
1150
1151         rc = tls_sw_fallback_init(sk, offload_ctx, crypto_info);
1152         if (rc)
1153                 goto free_offload_ctx;
1154
1155         /* start at rec_seq - 1 to account for the start marker record */
1156         memcpy(&rcd_sn, ctx->tx.rec_seq, sizeof(rcd_sn));
1157         offload_ctx->unacked_record_sn = be64_to_cpu(rcd_sn) - 1;
1158
1159         start_marker_record->end_seq = tcp_sk(sk)->write_seq;
1160         start_marker_record->len = 0;
1161         start_marker_record->num_frags = 0;
1162
1163         INIT_WORK(&offload_ctx->destruct_work, tls_device_tx_del_task);
1164         offload_ctx->ctx = ctx;
1165
1166         INIT_LIST_HEAD(&offload_ctx->records_list);
1167         list_add_tail(&start_marker_record->list, &offload_ctx->records_list);
1168         spin_lock_init(&offload_ctx->lock);
1169         sg_init_table(offload_ctx->sg_tx_data,
1170                       ARRAY_SIZE(offload_ctx->sg_tx_data));
1171
1172         clean_acked_data_enable(inet_csk(sk), &tls_icsk_clean_acked);
1173         ctx->push_pending_record = tls_device_push_pending_record;
1174
1175         /* TLS offload is greatly simplified if we don't send
1176          * SKBs where only part of the payload needs to be encrypted.
1177          * So mark the last skb in the write queue as end of record.
1178          */
1179         skb = tcp_write_queue_tail(sk);
1180         if (skb)
1181                 TCP_SKB_CB(skb)->eor = 1;
1182
1183         /* Avoid offloading if the device is down
1184          * We don't want to offload new flows after
1185          * the NETDEV_DOWN event
1186          *
1187          * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1188          * handler thus protecting from the device going down before
1189          * ctx was added to tls_device_list.
1190          */
1191         down_read(&device_offload_lock);
1192         if (!(netdev->flags & IFF_UP)) {
1193                 rc = -EINVAL;
1194                 goto release_lock;
1195         }
1196
1197         ctx->priv_ctx_tx = offload_ctx;
1198         rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
1199                                              &ctx->crypto_send.info,
1200                                              tcp_sk(sk)->write_seq);
1201         trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_TX,
1202                                      tcp_sk(sk)->write_seq, rec_seq, rc);
1203         if (rc)
1204                 goto release_lock;
1205
1206         tls_device_attach(ctx, sk, netdev);
1207         up_read(&device_offload_lock);
1208
1209         /* following this assignment tls_is_sk_tx_device_offloaded
1210          * will return true and the context might be accessed
1211          * by the netdev's xmit function.
1212          */
1213         smp_store_release(&sk->sk_validate_xmit_skb, tls_validate_xmit_skb);
1214         dev_put(netdev);
1215
1216         return 0;
1217
1218 release_lock:
1219         up_read(&device_offload_lock);
1220         clean_acked_data_disable(inet_csk(sk));
1221         crypto_free_aead(offload_ctx->aead_send);
1222 free_offload_ctx:
1223         kfree(offload_ctx);
1224         ctx->priv_ctx_tx = NULL;
1225 free_marker_record:
1226         kfree(start_marker_record);
1227 free_rec_seq:
1228         kfree(ctx->tx.rec_seq);
1229 free_iv:
1230         kfree(ctx->tx.iv);
1231 release_netdev:
1232         dev_put(netdev);
1233         return rc;
1234 }
1235
1236 int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
1237 {
1238         struct tls12_crypto_info_aes_gcm_128 *info;
1239         struct tls_offload_context_rx *context;
1240         struct net_device *netdev;
1241         int rc = 0;
1242
1243         if (ctx->crypto_recv.info.version != TLS_1_2_VERSION)
1244                 return -EOPNOTSUPP;
1245
1246         netdev = get_netdev_for_sock(sk);
1247         if (!netdev) {
1248                 pr_err_ratelimited("%s: netdev not found\n", __func__);
1249                 return -EINVAL;
1250         }
1251
1252         if (!(netdev->features & NETIF_F_HW_TLS_RX)) {
1253                 rc = -EOPNOTSUPP;
1254                 goto release_netdev;
1255         }
1256
1257         /* Avoid offloading if the device is down
1258          * We don't want to offload new flows after
1259          * the NETDEV_DOWN event
1260          *
1261          * device_offload_lock is taken in tls_devices's NETDEV_DOWN
1262          * handler thus protecting from the device going down before
1263          * ctx was added to tls_device_list.
1264          */
1265         down_read(&device_offload_lock);
1266         if (!(netdev->flags & IFF_UP)) {
1267                 rc = -EINVAL;
1268                 goto release_lock;
1269         }
1270
1271         context = kzalloc(TLS_OFFLOAD_CONTEXT_SIZE_RX, GFP_KERNEL);
1272         if (!context) {
1273                 rc = -ENOMEM;
1274                 goto release_lock;
1275         }
1276         context->resync_nh_reset = 1;
1277
1278         ctx->priv_ctx_rx = context;
1279         rc = tls_set_sw_offload(sk, ctx, 0);
1280         if (rc)
1281                 goto release_ctx;
1282
1283         rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_RX,
1284                                              &ctx->crypto_recv.info,
1285                                              tcp_sk(sk)->copied_seq);
1286         info = (void *)&ctx->crypto_recv.info;
1287         trace_tls_device_offload_set(sk, TLS_OFFLOAD_CTX_DIR_RX,
1288                                      tcp_sk(sk)->copied_seq, info->rec_seq, rc);
1289         if (rc)
1290                 goto free_sw_resources;
1291
1292         tls_device_attach(ctx, sk, netdev);
1293         up_read(&device_offload_lock);
1294
1295         dev_put(netdev);
1296
1297         return 0;
1298
1299 free_sw_resources:
1300         up_read(&device_offload_lock);
1301         tls_sw_free_resources_rx(sk);
1302         down_read(&device_offload_lock);
1303 release_ctx:
1304         ctx->priv_ctx_rx = NULL;
1305 release_lock:
1306         up_read(&device_offload_lock);
1307 release_netdev:
1308         dev_put(netdev);
1309         return rc;
1310 }
1311
1312 void tls_device_offload_cleanup_rx(struct sock *sk)
1313 {
1314         struct tls_context *tls_ctx = tls_get_ctx(sk);
1315         struct net_device *netdev;
1316
1317         down_read(&device_offload_lock);
1318         netdev = rcu_dereference_protected(tls_ctx->netdev,
1319                                            lockdep_is_held(&device_offload_lock));
1320         if (!netdev)
1321                 goto out;
1322
1323         netdev->tlsdev_ops->tls_dev_del(netdev, tls_ctx,
1324                                         TLS_OFFLOAD_CTX_DIR_RX);
1325
1326         if (tls_ctx->tx_conf != TLS_HW) {
1327                 dev_put(netdev);
1328                 rcu_assign_pointer(tls_ctx->netdev, NULL);
1329         } else {
1330                 set_bit(TLS_RX_DEV_CLOSED, &tls_ctx->flags);
1331         }
1332 out:
1333         up_read(&device_offload_lock);
1334         tls_sw_release_resources_rx(sk);
1335 }
1336
1337 static int tls_device_down(struct net_device *netdev)
1338 {
1339         struct tls_context *ctx, *tmp;
1340         unsigned long flags;
1341         LIST_HEAD(list);
1342
1343         /* Request a write lock to block new offload attempts */
1344         down_write(&device_offload_lock);
1345
1346         spin_lock_irqsave(&tls_device_lock, flags);
1347         list_for_each_entry_safe(ctx, tmp, &tls_device_list, list) {
1348                 struct net_device *ctx_netdev =
1349                         rcu_dereference_protected(ctx->netdev,
1350                                                   lockdep_is_held(&device_offload_lock));
1351
1352                 if (ctx_netdev != netdev ||
1353                     !refcount_inc_not_zero(&ctx->refcount))
1354                         continue;
1355
1356                 list_move(&ctx->list, &list);
1357         }
1358         spin_unlock_irqrestore(&tls_device_lock, flags);
1359
1360         list_for_each_entry_safe(ctx, tmp, &list, list) {
1361                 /* Stop offloaded TX and switch to the fallback.
1362                  * tls_is_sk_tx_device_offloaded will return false.
1363                  */
1364                 WRITE_ONCE(ctx->sk->sk_validate_xmit_skb, tls_validate_xmit_skb_sw);
1365
1366                 /* Stop the RX and TX resync.
1367                  * tls_dev_resync must not be called after tls_dev_del.
1368                  */
1369                 rcu_assign_pointer(ctx->netdev, NULL);
1370
1371                 /* Start skipping the RX resync logic completely. */
1372                 set_bit(TLS_RX_DEV_DEGRADED, &ctx->flags);
1373
1374                 /* Sync with inflight packets. After this point:
1375                  * TX: no non-encrypted packets will be passed to the driver.
1376                  * RX: resync requests from the driver will be ignored.
1377                  */
1378                 synchronize_net();
1379
1380                 /* Release the offload context on the driver side. */
1381                 if (ctx->tx_conf == TLS_HW)
1382                         netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1383                                                         TLS_OFFLOAD_CTX_DIR_TX);
1384                 if (ctx->rx_conf == TLS_HW &&
1385                     !test_bit(TLS_RX_DEV_CLOSED, &ctx->flags))
1386                         netdev->tlsdev_ops->tls_dev_del(netdev, ctx,
1387                                                         TLS_OFFLOAD_CTX_DIR_RX);
1388
1389                 dev_put(netdev);
1390
1391                 /* Move the context to a separate list for two reasons:
1392                  * 1. When the context is deallocated, list_del is called.
1393                  * 2. It's no longer an offloaded context, so we don't want to
1394                  *    run offload-specific code on this context.
1395                  */
1396                 spin_lock_irqsave(&tls_device_lock, flags);
1397                 list_move_tail(&ctx->list, &tls_device_down_list);
1398                 spin_unlock_irqrestore(&tls_device_lock, flags);
1399
1400                 /* Device contexts for RX and TX will be freed in on sk_destruct
1401                  * by tls_device_free_ctx. rx_conf and tx_conf stay in TLS_HW.
1402                  * Now release the ref taken above.
1403                  */
1404                 if (refcount_dec_and_test(&ctx->refcount)) {
1405                         /* sk_destruct ran after tls_device_down took a ref, and
1406                          * it returned early. Complete the destruction here.
1407                          */
1408                         list_del(&ctx->list);
1409                         tls_device_free_ctx(ctx);
1410                 }
1411         }
1412
1413         up_write(&device_offload_lock);
1414
1415         flush_workqueue(destruct_wq);
1416
1417         return NOTIFY_DONE;
1418 }
1419
1420 static int tls_dev_event(struct notifier_block *this, unsigned long event,
1421                          void *ptr)
1422 {
1423         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1424
1425         if (!dev->tlsdev_ops &&
1426             !(dev->features & (NETIF_F_HW_TLS_RX | NETIF_F_HW_TLS_TX)))
1427                 return NOTIFY_DONE;
1428
1429         switch (event) {
1430         case NETDEV_REGISTER:
1431         case NETDEV_FEAT_CHANGE:
1432                 if (netif_is_bond_master(dev))
1433                         return NOTIFY_DONE;
1434                 if ((dev->features & NETIF_F_HW_TLS_RX) &&
1435                     !dev->tlsdev_ops->tls_dev_resync)
1436                         return NOTIFY_BAD;
1437
1438                 if  (dev->tlsdev_ops &&
1439                      dev->tlsdev_ops->tls_dev_add &&
1440                      dev->tlsdev_ops->tls_dev_del)
1441                         return NOTIFY_DONE;
1442                 else
1443                         return NOTIFY_BAD;
1444         case NETDEV_DOWN:
1445                 return tls_device_down(dev);
1446         }
1447         return NOTIFY_DONE;
1448 }
1449
1450 static struct notifier_block tls_dev_notifier = {
1451         .notifier_call  = tls_dev_event,
1452 };
1453
1454 int __init tls_device_init(void)
1455 {
1456         int err;
1457
1458         dummy_page = alloc_page(GFP_KERNEL);
1459         if (!dummy_page)
1460                 return -ENOMEM;
1461
1462         destruct_wq = alloc_workqueue("ktls_device_destruct", 0, 0);
1463         if (!destruct_wq) {
1464                 err = -ENOMEM;
1465                 goto err_free_dummy;
1466         }
1467
1468         err = register_netdevice_notifier(&tls_dev_notifier);
1469         if (err)
1470                 goto err_destroy_wq;
1471
1472         return 0;
1473
1474 err_destroy_wq:
1475         destroy_workqueue(destruct_wq);
1476 err_free_dummy:
1477         put_page(dummy_page);
1478         return err;
1479 }
1480
1481 void __exit tls_device_cleanup(void)
1482 {
1483         unregister_netdevice_notifier(&tls_dev_notifier);
1484         destroy_workqueue(destruct_wq);
1485         clean_acked_data_flush();
1486         put_page(dummy_page);
1487 }