Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
// SPDX-License-Identifier: GPL-2.0
// Copyright (c) 2010-2011 EIA Electronics,
//                         Pieter Beyens <pieter.beyens@eia.be>
// Copyright (c) 2010-2011 EIA Electronics,
//                         Kurt Van Dijck <kurt.van.dijck@eia.be>
// Copyright (c) 2018 Protonic,
//                         Robin van der Gracht <robin@protonic.nl>
// Copyright (c) 2017-2019 Pengutronix,
//                         Marc Kleine-Budde <kernel@pengutronix.de>
// Copyright (c) 2017-2019 Pengutronix,
//                         Oleksij Rempel <kernel@pengutronix.de>

#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/can/core.h>
#include <linux/can/skb.h>
#include <linux/errqueue.h>
#include <linux/if_arp.h>

#include "j1939-priv.h"

#define J1939_MIN_NAMELEN CAN_REQUIRED_SIZE(struct sockaddr_can, can_addr.j1939)

/* conversion function between struct sock::sk_priority from linux and
 * j1939 priority field
 */
static inline priority_t j1939_prio(u32 sk_priority)
{
	sk_priority = min(sk_priority, 7U);

	return 7 - sk_priority;
}

static inline u32 j1939_to_sk_priority(priority_t prio)
{
	return 7 - prio;
}

/* function to see if pgn is to be evaluated */
static inline bool j1939_pgn_is_valid(pgn_t pgn)
{
	return pgn <= J1939_PGN_MAX;
}

/* test function to avoid non-zero DA placeholder for pdu1 pgn's */
static inline bool j1939_pgn_is_clean_pdu(pgn_t pgn)
{
	if (j1939_pgn_is_pdu1(pgn))
		return !(pgn & 0xff);
	else
		return true;
}

static inline void j1939_sock_pending_add(struct sock *sk)
{
	struct j1939_sock *jsk = j1939_sk(sk);

	atomic_inc(&jsk->skb_pending);
}

static int j1939_sock_pending_get(struct sock *sk)
{
	struct j1939_sock *jsk = j1939_sk(sk);

	return atomic_read(&jsk->skb_pending);
}

void j1939_sock_pending_del(struct sock *sk)
{
	struct j1939_sock *jsk = j1939_sk(sk);

	/* atomic_dec_return returns the new value */
	if (!atomic_dec_return(&jsk->skb_pending))
		wake_up(&jsk->waitq);	/* no pending SKB's */
}

static void j1939_jsk_add(struct j1939_priv *priv, struct j1939_sock *jsk)
{
	jsk->state |= J1939_SOCK_BOUND;
	j1939_priv_get(priv);

	spin_lock_bh(&priv->j1939_socks_lock);
	list_add_tail(&jsk->list, &priv->j1939_socks);
	spin_unlock_bh(&priv->j1939_socks_lock);
}

static void j1939_jsk_del(struct j1939_priv *priv, struct j1939_sock *jsk)
{
	spin_lock_bh(&priv->j1939_socks_lock);
	list_del_init(&jsk->list);
	spin_unlock_bh(&priv->j1939_socks_lock);

	j1939_priv_put(priv);
	jsk->state &= ~J1939_SOCK_BOUND;
}

static bool j1939_sk_queue_session(struct j1939_session *session)
{
	struct j1939_sock *jsk = j1939_sk(session->sk);
	bool empty;

	spin_lock_bh(&jsk->sk_session_queue_lock);
	empty = list_empty(&jsk->sk_session_queue);
	j1939_session_get(session);
	list_add_tail(&session->sk_session_queue_entry, &jsk->sk_session_queue);
	spin_unlock_bh(&jsk->sk_session_queue_lock);
	j1939_sock_pending_add(&jsk->sk);

	return empty;
}

static struct
j1939_session *j1939_sk_get_incomplete_session(struct j1939_sock *jsk)
{
	struct j1939_session *session = NULL;

	spin_lock_bh(&jsk->sk_session_queue_lock);
	if (!list_empty(&jsk->sk_session_queue)) {
		session = list_last_entry(&jsk->sk_session_queue,
					  struct j1939_session,
					  sk_session_queue_entry);
		if (session->total_queued_size == session->total_message_size)
			session = NULL;
		else
			j1939_session_get(session);
	}
	spin_unlock_bh(&jsk->sk_session_queue_lock);

	return session;
}

static void j1939_sk_queue_drop_all(struct j1939_priv *priv,
				    struct j1939_sock *jsk, int err)
{
	struct j1939_session *session, *tmp;

	netdev_dbg(priv->ndev, "%s: err: %i\n", __func__, err);
	spin_lock_bh(&jsk->sk_session_queue_lock);
	list_for_each_entry_safe(session, tmp, &jsk->sk_session_queue,
				 sk_session_queue_entry) {
		list_del_init(&session->sk_session_queue_entry);
		session->err = err;
		j1939_session_put(session);
	}
	spin_unlock_bh(&jsk->sk_session_queue_lock);
}

static void j1939_sk_queue_activate_next_locked(struct j1939_session *session)
{
	struct j1939_sock *jsk;
	struct j1939_session *first;
	int err;

	/* RX-Session don't have a socket (yet) */
	if (!session->sk)
		return;

	jsk = j1939_sk(session->sk);
	lockdep_assert_held(&jsk->sk_session_queue_lock);

	err = session->err;

	first = list_first_entry_or_null(&jsk->sk_session_queue,
					 struct j1939_session,
					 sk_session_queue_entry);

	/* Some else has already activated the next session */
	if (first != session)
		return;

activate_next:
	list_del_init(&first->sk_session_queue_entry);
	j1939_session_put(first);
	first = list_first_entry_or_null(&jsk->sk_session_queue,
					 struct j1939_session,
					 sk_session_queue_entry);
	if (!first)
		return;

	if (WARN_ON_ONCE(j1939_session_activate(first))) {
		first->err = -EBUSY;
		goto activate_next;
	} else {
		/* Give receiver some time (arbitrary chosen) to recover */
		int time_ms = 0;

		if (err)
			time_ms = 10 + prandom_u32_max(16);

		j1939_tp_schedule_txtimer(first, time_ms);
	}
}

void j1939_sk_queue_activate_next(struct j1939_session *session)
{
	struct j1939_sock *jsk;

	if (!session->sk)
		return;

	jsk = j1939_sk(session->sk);

	spin_lock_bh(&jsk->sk_session_queue_lock);
	j1939_sk_queue_activate_next_locked(session);
	spin_unlock_bh(&jsk->sk_session_queue_lock);
}

static bool j1939_sk_match_dst(struct j1939_sock *jsk,
			       const struct j1939_sk_buff_cb *skcb)
{
	if ((jsk->state & J1939_SOCK_PROMISC))
		return true;

	/* Destination address filter */
	if (jsk->addr.src_name && skcb->addr.dst_name) {
		if (jsk->addr.src_name != skcb->addr.dst_name)
			return false;
	} else {
		/* receive (all sockets) if
		 * - all packages that match our bind() address
		 * - all broadcast on a socket if SO_BROADCAST
		 *   is set
		 */
		if (j1939_address_is_unicast(skcb->addr.da)) {
			if (jsk->addr.sa != skcb->addr.da)
				return false;
		} else if (!sock_flag(&jsk->sk, SOCK_BROADCAST)) {
			/* receiving broadcast without SO_BROADCAST
			 * flag is not allowed
			 */
			return false;
		}
	}

	/* Source address filter */
	if (jsk->state & J1939_SOCK_CONNECTED) {
		/* receive (all sockets) if
		 * - all packages that match our connect() name or address
		 */
		if (jsk->addr.dst_name && skcb->addr.src_name) {
			if (jsk->addr.dst_name != skcb->addr.src_name)
				return false;
		} else {
			if (jsk->addr.da != skcb->addr.sa)
				return false;
		}
	}

	/* PGN filter */
	if (j1939_pgn_is_valid(jsk->pgn_rx_filter) &&
	    jsk->pgn_rx_filter != skcb->addr.pgn)
		return false;

	return true;
}

/* matches skb control buffer (addr) with a j1939 filter */
static bool j1939_sk_match_filter(struct j1939_sock *jsk,
				  const struct j1939_sk_buff_cb *skcb)
{
	const struct j1939_filter *f = jsk->filters;
	int nfilter = jsk->nfilters;

	if (!nfilter)
		/* receive all when no filters are assigned */
		return true;

	for (; nfilter; ++f, --nfilter) {
		if ((skcb->addr.pgn & f->pgn_mask) != f->pgn)
			continue;
		if ((skcb->addr.sa & f->addr_mask) != f->addr)
			continue;
		if ((skcb->addr.src_name & f->name_mask) != f->name)
			continue;
		return true;
	}
	return false;
}

static bool j1939_sk_recv_match_one(struct j1939_sock *jsk,
				    const struct j1939_sk_buff_cb *skcb)
{
	if (!(jsk->state & J1939_SOCK_BOUND))
		return false;

	if (!j1939_sk_match_dst(jsk, skcb))
		return false;

	if (!j1939_sk_match_filter(jsk, skcb))
		return false;

	return true;
}

static void j1939_sk_recv_one(struct j1939_sock *jsk, struct sk_buff *oskb)
{
	const struct j1939_sk_buff_cb *oskcb = j1939_skb_to_cb(oskb);
	struct j1939_sk_buff_cb *skcb;
	struct sk_buff *skb;

	if (oskb->sk == &jsk->sk)
		return;

	if (!j1939_sk_recv_match_one(jsk, oskcb))
		return;

	skb = skb_clone(oskb, GFP_ATOMIC);
	if (!skb) {
		pr_warn("skb clone failed\n");
		return;
	}
	can_skb_set_owner(skb, oskb->sk);

	skcb = j1939_skb_to_cb(skb);
	skcb->msg_flags &= ~(MSG_DONTROUTE);
	if (skb->sk)
		skcb->msg_flags |= MSG_DONTROUTE;

	if (sock_queue_rcv_skb(&jsk->sk, skb) < 0)
		kfree_skb(skb);
}

bool j1939_sk_recv_match(struct j1939_priv *priv, struct j1939_sk_buff_cb *skcb)
{
	struct j1939_sock *jsk;
	bool match = false;

	spin_lock_bh(&priv->j1939_socks_lock);
	list_for_each_entry(jsk, &priv->j1939_socks, list) {
		match = j1939_sk_recv_match_one(jsk, skcb);
		if (match)
			break;
	}
	spin_unlock_bh(&priv->j1939_socks_lock);

	return match;
}

void j1939_sk_recv(struct j1939_priv *priv, struct sk_buff *skb)
{
	struct j1939_sock *jsk;

	spin_lock_bh(&priv->j1939_socks_lock);
	list_for_each_entry(jsk, &priv->j1939_socks, list) {
		j1939_sk_recv_one(jsk, skb);
	}
	spin_unlock_bh(&priv->j1939_socks_lock);
}

static void j1939_sk_sock_destruct(struct sock *sk)
{
	struct j1939_sock *jsk = j1939_sk(sk);

	/* This function will be call by the generic networking code, when then
	 * the socket is ultimately closed (sk->sk_destruct).
	 *
	 * The race between
	 * - processing a received CAN frame
	 *   (can_receive -> j1939_can_recv)
	 *   and accessing j1939_priv
	 * ... and ...
	 * - closing a socket
	 *   (j1939_can_rx_unregister -> can_rx_unregister)
	 *   and calling the final j1939_priv_put()
	 *
	 * is avoided by calling the final j1939_priv_put() from this
	 * RCU deferred cleanup call.
	 */
	if (jsk->priv) {
		j1939_priv_put(jsk->priv);
		jsk->priv = NULL;
	}

	/* call generic CAN sock destruct */
	can_sock_destruct(sk);
}

static int j1939_sk_init(struct sock *sk)
{
	struct j1939_sock *jsk = j1939_sk(sk);

	/* Ensure that "sk" is first member in "struct j1939_sock", so that we
	 * can skip it during memset().
	 */
	BUILD_BUG_ON(offsetof(struct j1939_sock, sk) != 0);
	memset((void *)jsk + sizeof(jsk->sk), 0x0,
	       sizeof(*jsk) - sizeof(jsk->sk));

	INIT_LIST_HEAD(&jsk->list);
	init_waitqueue_head(&jsk->waitq);
	jsk->sk.sk_priority = j1939_to_sk_priority(6);
	jsk->sk.sk_reuse = 1; /* per default */
	jsk->addr.sa = J1939_NO_ADDR;
	jsk->addr.da = J1939_NO_ADDR;
	jsk->addr.pgn = J1939_NO_PGN;
	jsk->pgn_rx_filter = J1939_NO_PGN;
	atomic_set(&jsk->skb_pending, 0);
	spin_lock_init(&jsk->sk_session_queue_lock);
	INIT_LIST_HEAD(&jsk->sk_session_queue);
	sk->sk_destruct = j1939_sk_sock_destruct;

	return 0;
}

static int j1939_sk_sanity_check(struct sockaddr_can *addr, int len)
{
	if (!addr)
		return -EDESTADDRREQ;
	if (len < J1939_MIN_NAMELEN)
		return -EINVAL;
	if (addr->can_family != AF_CAN)
		return -EINVAL;
	if (!addr->can_ifindex)
		return -ENODEV;
	if (j1939_pgn_is_valid(addr->can_addr.j1939.pgn) &&
	    !j1939_pgn_is_clean_pdu(addr->can_addr.j1939.pgn))
		return -EINVAL;

	return 0;
}

static int j1939_sk_bind(struct socket *sock, struct sockaddr *uaddr, int len)
{
	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
	struct j1939_sock *jsk = j1939_sk(sock->sk);
	struct j1939_priv *priv = jsk->priv;
	struct sock *sk = sock->sk;
	struct net *net = sock_net(sk);
	int ret = 0;

	ret = j1939_sk_sanity_check(addr, len);
	if (ret)
		return ret;

	lock_sock(sock->sk);

	/* Already bound to an interface? */
	if (jsk->state & J1939_SOCK_BOUND) {
		/* A re-bind() to a different interface is not
		 * supported.
		 */
		if (jsk->ifindex != addr->can_ifindex) {
			ret = -EINVAL;
			goto out_release_sock;
		}

		/* drop old references */
		j1939_jsk_del(priv, jsk);
		j1939_local_ecu_put(priv, jsk->addr.src_name, jsk->addr.sa);
	} else {
		struct net_device *ndev;

		ndev = dev_get_by_index(net, addr->can_ifindex);
		if (!ndev) {
			ret = -ENODEV;
			goto out_release_sock;
		}

		if (ndev->type != ARPHRD_CAN) {
			dev_put(ndev);
			ret = -ENODEV;
			goto out_release_sock;
		}

		priv = j1939_netdev_start(ndev);
		dev_put(ndev);
		if (IS_ERR(priv)) {
			ret = PTR_ERR(priv);
			goto out_release_sock;
		}

		jsk->ifindex = addr->can_ifindex;

		/* the corresponding j1939_priv_put() is called via
		 * sk->sk_destruct, which points to j1939_sk_sock_destruct()
		 */
		j1939_priv_get(priv);
		jsk->priv = priv;
	}

	/* set default transmit pgn */
	if (j1939_pgn_is_valid(addr->can_addr.j1939.pgn))
		jsk->pgn_rx_filter = addr->can_addr.j1939.pgn;
	jsk->addr.src_name = addr->can_addr.j1939.name;
	jsk->addr.sa = addr->can_addr.j1939.addr;

	/* get new references */
	ret = j1939_local_ecu_get(priv, jsk->addr.src_name, jsk->addr.sa);
	if (ret) {
		j1939_netdev_stop(priv);
		goto out_release_sock;
	}

	j1939_jsk_add(priv, jsk);

 out_release_sock: /* fall through */
	release_sock(sock->sk);

	return ret;
}

static int j1939_sk_connect(struct socket *sock, struct sockaddr *uaddr,
			    int len, int flags)
{
	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
	struct j1939_sock *jsk = j1939_sk(sock->sk);
	int ret = 0;

	ret = j1939_sk_sanity_check(addr, len);
	if (ret)
		return ret;

	lock_sock(sock->sk);

	/* bind() before connect() is mandatory */
	if (!(jsk->state & J1939_SOCK_BOUND)) {
		ret = -EINVAL;
		goto out_release_sock;
	}

	/* A connect() to a different interface is not supported. */
	if (jsk->ifindex != addr->can_ifindex) {
		ret = -EINVAL;
		goto out_release_sock;
	}

	if (!addr->can_addr.j1939.name &&
	    addr->can_addr.j1939.addr == J1939_NO_ADDR &&
	    !sock_flag(&jsk->sk, SOCK_BROADCAST)) {
		/* broadcast, but SO_BROADCAST not set */
		ret = -EACCES;
		goto out_release_sock;
	}

	jsk->addr.dst_name = addr->can_addr.j1939.name;
	jsk->addr.da = addr->can_addr.j1939.addr;

	if (j1939_pgn_is_valid(addr->can_addr.j1939.pgn))
		jsk->addr.pgn = addr->can_addr.j1939.pgn;

	jsk->state |= J1939_SOCK_CONNECTED;

 out_release_sock: /* fall through */
	release_sock(sock->sk);

	return ret;
}

static void j1939_sk_sock2sockaddr_can(struct sockaddr_can *addr,
				       const struct j1939_sock *jsk, int peer)
{
	addr->can_family = AF_CAN;
	addr->can_ifindex = jsk->ifindex;
	addr->can_addr.j1939.pgn = jsk->addr.pgn;
	if (peer) {
		addr->can_addr.j1939.name = jsk->addr.dst_name;
		addr->can_addr.j1939.addr = jsk->addr.da;
	} else {
		addr->can_addr.j1939.name = jsk->addr.src_name;
		addr->can_addr.j1939.addr = jsk->addr.sa;
	}
}

static int j1939_sk_getname(struct socket *sock, struct sockaddr *uaddr,
			    int peer)
{
	struct sockaddr_can *addr = (struct sockaddr_can *)uaddr;
	struct sock *sk = sock->sk;
	struct j1939_sock *jsk = j1939_sk(sk);
	int ret = 0;

	lock_sock(sk);

	if (peer && !(jsk->state & J1939_SOCK_CONNECTED)) {
		ret = -EADDRNOTAVAIL;
		goto failure;
	}

	j1939_sk_sock2sockaddr_can(addr, jsk, peer);
	ret = J1939_MIN_NAMELEN;

 failure:
	release_sock(sk);

	return ret;
}

static int j1939_sk_release(struct socket *sock)
{
	struct sock *sk = sock->sk;
	struct j1939_sock *jsk;

	if (!sk)
		return 0;

	lock_sock(sk);
	jsk = j1939_sk(sk);

	if (jsk->state & J1939_SOCK_BOUND) {
		struct j1939_priv *priv = jsk->priv;

		if (wait_event_interruptible(jsk->waitq,
					     !j1939_sock_pending_get(&jsk->sk))) {
			j1939_cancel_active_session(priv, sk);
			j1939_sk_queue_drop_all(priv, jsk, ESHUTDOWN);
		}

		j1939_jsk_del(priv, jsk);

		j1939_local_ecu_put(priv, jsk->addr.src_name,
				    jsk->addr.sa);

		j1939_netdev_stop(priv);
	}

	kfree(jsk->filters);
	sock_orphan(sk);
	sock->sk = NULL;

	release_sock(sk);
	sock_put(sk);

	return 0;
}

static int j1939_sk_setsockopt_flag(struct j1939_sock *jsk, char __user *optval,
				    unsigned int optlen, int flag)
{
	int tmp;

	if (optlen != sizeof(tmp))
		return -EINVAL;
	if (copy_from_user(&tmp, optval, optlen))
		return -EFAULT;
	lock_sock(&jsk->sk);
	if (tmp)
		jsk->state |= flag;
	else
		jsk->state &= ~flag;
	release_sock(&jsk->sk);
	return tmp;
}

static int j1939_sk_setsockopt(struct socket *sock, int level, int optname,
			       char __user *optval, unsigned int optlen)
{
	struct sock *sk = sock->sk;
	struct j1939_sock *jsk = j1939_sk(sk);
	int tmp, count = 0, ret = 0;
	struct j1939_filter *filters = NULL, *ofilters;

	if (level != SOL_CAN_J1939)
		return -EINVAL;

	switch (optname) {
	case SO_J1939_FILTER:
		if (optval) {
			struct j1939_filter *f;
			int c;

			if (optlen % sizeof(*filters) != 0)
				return -EINVAL;

			if (optlen > J1939_FILTER_MAX *
			    sizeof(struct j1939_filter))
				return -EINVAL;

			count = optlen / sizeof(*filters);
			filters = memdup_user(optval, optlen);
			if (IS_ERR(filters))
				return PTR_ERR(filters);

			for (f = filters, c = count; c; f++, c--) {
				f->name &= f->name_mask;
				f->pgn &= f->pgn_mask;
				f->addr &= f->addr_mask;
			}
		}

		lock_sock(&jsk->sk);
		ofilters = jsk->filters;
		jsk->filters = filters;
		jsk->nfilters = count;
		release_sock(&jsk->sk);
		kfree(ofilters);
		return 0;
	case SO_J1939_PROMISC:
		return j1939_sk_setsockopt_flag(jsk, optval, optlen,
						J1939_SOCK_PROMISC);
	case SO_J1939_ERRQUEUE:
		ret = j1939_sk_setsockopt_flag(jsk, optval, optlen,
					       J1939_SOCK_ERRQUEUE);
		if (ret < 0)
			return ret;

		if (!(jsk->state & J1939_SOCK_ERRQUEUE))
			skb_queue_purge(&sk->sk_error_queue);
		return ret;
	case SO_J1939_SEND_PRIO:
		if (optlen != sizeof(tmp))
			return -EINVAL;
		if (copy_from_user(&tmp, optval, optlen))
			return -EFAULT;
		if (tmp < 0 || tmp > 7)
			return -EDOM;
		if (tmp < 2 && !capable(CAP_NET_ADMIN))
			return -EPERM;
		lock_sock(&jsk->sk);
		jsk->sk.sk_priority = j1939_to_sk_priority(tmp);
		release_sock(&jsk->sk);
		return 0;
	default:
		return -ENOPROTOOPT;
	}
}

static int j1939_sk_getsockopt(struct socket *sock, int level, int optname,
			       char __user *optval, int __user *optlen)
{
	struct sock *sk = sock->sk;
	struct j1939_sock *jsk = j1939_sk(sk);
	int ret, ulen;
	/* set defaults for using 'int' properties */
	int tmp = 0;
	int len = sizeof(tmp);
	void *val = &tmp;

	if (level != SOL_CAN_J1939)
		return -EINVAL;
	if (get_user(ulen, optlen))
		return -EFAULT;
	if (ulen < 0)
		return -EINVAL;

	lock_sock(&jsk->sk);
	switch (optname) {
	case SO_J1939_PROMISC:
		tmp = (jsk->state & J1939_SOCK_PROMISC) ? 1 : 0;
		break;
	case SO_J1939_ERRQUEUE:
		tmp = (jsk->state & J1939_SOCK_ERRQUEUE) ? 1 : 0;
		break;
	case SO_J1939_SEND_PRIO:
		tmp = j1939_prio(jsk->sk.sk_priority);
		break;
	default:
		ret = -ENOPROTOOPT;
		goto no_copy;
	}

	/* copy to user, based on 'len' & 'val'
	 * but most sockopt's are 'int' properties, and have 'len' & 'val'
	 * left unchanged, but instead modified 'tmp'
	 */
	if (len > ulen)
		ret = -EFAULT;
	else if (put_user(len, optlen))
		ret = -EFAULT;
	else if (copy_to_user(optval, val, len))
		ret = -EFAULT;
	else
		ret = 0;
 no_copy:
	release_sock(&jsk->sk);
	return ret;
}

static int j1939_sk_recvmsg(struct socket *sock, struct msghdr *msg,
			    size_t size, int flags)
{
	struct sock *sk = sock->sk;
	struct sk_buff *skb;
	struct j1939_sk_buff_cb *skcb;
	int ret = 0;

	if (flags & ~(MSG_DONTWAIT | MSG_ERRQUEUE))
		return -EINVAL;

	if (flags & MSG_ERRQUEUE)
		return sock_recv_errqueue(sock->sk, msg, size, SOL_CAN_J1939,
					  SCM_J1939_ERRQUEUE);

	skb = skb_recv_datagram(sk, flags, 0, &ret);
	if (!skb)
		return ret;

	if (size < skb->len)
		msg->msg_flags |= MSG_TRUNC;
	else
		size = skb->len;

	ret = memcpy_to_msg(msg, skb->data, size);
	if (ret < 0) {
		skb_free_datagram(sk, skb);
		return ret;
	}

	skcb = j1939_skb_to_cb(skb);
	if (j1939_address_is_valid(skcb->addr.da))
		put_cmsg(msg, SOL_CAN_J1939, SCM_J1939_DEST_ADDR,
			 sizeof(skcb->addr.da), &skcb->addr.da);

	if (skcb->addr.dst_name)
		put_cmsg(msg, SOL_CAN_J1939, SCM_J1939_DEST_NAME,
			 sizeof(skcb->addr.dst_name), &skcb->addr.dst_name);

	put_cmsg(msg, SOL_CAN_J1939, SCM_J1939_PRIO,
		 sizeof(skcb->priority), &skcb->priority);

	if (msg->msg_name) {
		struct sockaddr_can *paddr = msg->msg_name;

		msg->msg_namelen = J1939_MIN_NAMELEN;
		memset(msg->msg_name, 0, msg->msg_namelen);
		paddr->can_family = AF_CAN;
		paddr->can_ifindex = skb->skb_iif;
		paddr->can_addr.j1939.name = skcb->addr.src_name;
		paddr->can_addr.j1939.addr = skcb->addr.sa;
		paddr->can_addr.j1939.pgn = skcb->addr.pgn;
	}

	sock_recv_ts_and_drops(msg, sk, skb);
	msg->msg_flags |= skcb->msg_flags;
	skb_free_datagram(sk, skb);

	return size;
}

static struct sk_buff *j1939_sk_alloc_skb(struct net_device *ndev,
					  struct sock *sk,
					  struct msghdr *msg, size_t size,
					  int *errcode)
{
	struct j1939_sock *jsk = j1939_sk(sk);
	struct j1939_sk_buff_cb *skcb;
	struct sk_buff *skb;
	int ret;

	skb = sock_alloc_send_skb(sk,
				  size +
				  sizeof(struct can_frame) -
				  sizeof(((struct can_frame *)NULL)->data) +
				  sizeof(struct can_skb_priv),
				  msg->msg_flags & MSG_DONTWAIT, &ret);
	if (!skb)
		goto failure;

	can_skb_reserve(skb);
	can_skb_prv(skb)->ifindex = ndev->ifindex;
	can_skb_prv(skb)->skbcnt = 0;
	skb_reserve(skb, offsetof(struct can_frame, data));

	ret = memcpy_from_msg(skb_put(skb, size), msg, size);
	if (ret < 0)
		goto free_skb;

	skb->dev = ndev;

	skcb = j1939_skb_to_cb(skb);
	memset(skcb, 0, sizeof(*skcb));
	skcb->addr = jsk->addr;
	skcb->priority = j1939_prio(sk->sk_priority);

	if (msg->msg_name) {
		struct sockaddr_can *addr = msg->msg_name;

		if (addr->can_addr.j1939.name ||
		    addr->can_addr.j1939.addr != J1939_NO_ADDR) {
			skcb->addr.dst_name = addr->can_addr.j1939.name;
			skcb->addr.da = addr->can_addr.j1939.addr;
		}
		if (j1939_pgn_is_valid(addr->can_addr.j1939.pgn))
			skcb->addr.pgn = addr->can_addr.j1939.pgn;
	}

	*errcode = ret;
	return skb;

free_skb:
	kfree_skb(skb);
failure:
	*errcode = ret;
	return NULL;
}

static size_t j1939_sk_opt_stats_get_size(void)
{
	return
		nla_total_size(sizeof(u32)) + /* J1939_NLA_BYTES_ACKED */
		0;
}

static struct sk_buff *
j1939_sk_get_timestamping_opt_stats(struct j1939_session *session)
{
	struct sk_buff *stats;
	u32 size;

	stats = alloc_skb(j1939_sk_opt_stats_get_size(), GFP_ATOMIC);
	if (!stats)
		return NULL;

	if (session->skcb.addr.type == J1939_SIMPLE)
		size = session->total_message_size;
	else
		size = min(session->pkt.tx_acked * 7,
			   session->total_message_size);

	nla_put_u32(stats, J1939_NLA_BYTES_ACKED, size);

	return stats;
}

void j1939_sk_errqueue(struct j1939_session *session,
		       enum j1939_sk_errqueue_type type)
{
	struct j1939_priv *priv = session->priv;
	struct sock *sk = session->sk;
	struct j1939_sock *jsk;
	struct sock_exterr_skb *serr;
	struct sk_buff *skb;
	char *state = "UNK";
	int err;

	/* currently we have no sk for the RX session */
	if (!sk)
		return;

	jsk = j1939_sk(sk);

	if (!(jsk->state & J1939_SOCK_ERRQUEUE))
		return;

	skb = j1939_sk_get_timestamping_opt_stats(session);
	if (!skb)
		return;

	skb->tstamp = ktime_get_real();

	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));

	serr = SKB_EXT_ERR(skb);
	memset(serr, 0, sizeof(*serr));
	switch (type) {
	case J1939_ERRQUEUE_ACK:
		if (!(sk->sk_tsflags & SOF_TIMESTAMPING_TX_ACK)) {
			kfree_skb(skb);
			return;
		}

		serr->ee.ee_errno = ENOMSG;
		serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
		serr->ee.ee_info = SCM_TSTAMP_ACK;
		state = "ACK";
		break;
	case J1939_ERRQUEUE_SCHED:
		if (!(sk->sk_tsflags & SOF_TIMESTAMPING_TX_SCHED)) {
			kfree_skb(skb);
			return;
		}

		serr->ee.ee_errno = ENOMSG;
		serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
		serr->ee.ee_info = SCM_TSTAMP_SCHED;
		state = "SCH";
		break;
	case J1939_ERRQUEUE_ABORT:
		serr->ee.ee_errno = session->err;
		serr->ee.ee_origin = SO_EE_ORIGIN_LOCAL;
		serr->ee.ee_info = J1939_EE_INFO_TX_ABORT;
		state = "ABT";
		break;
	default:
		netdev_err(priv->ndev, "Unknown errqueue type %i\n", type);
	}

	serr->opt_stats = true;
	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)
		serr->ee.ee_data = session->tskey;

	netdev_dbg(session->priv->ndev, "%s: 0x%p tskey: %i, state: %s\n",
		   __func__, session, session->tskey, state);
	err = sock_queue_err_skb(sk, skb);

	if (err)
		kfree_skb(skb);
};

void j1939_sk_send_loop_abort(struct sock *sk, int err)
{
	sk->sk_err = err;

	sk->sk_error_report(sk);
}

static int j1939_sk_send_loop(struct j1939_priv *priv,  struct sock *sk,
			      struct msghdr *msg, size_t size)

{
	struct j1939_sock *jsk = j1939_sk(sk);
	struct j1939_session *session = j1939_sk_get_incomplete_session(jsk);
	struct sk_buff *skb;
	size_t segment_size, todo_size;
	int ret = 0;

	if (session &&
	    session->total_message_size != session->total_queued_size + size) {
		j1939_session_put(session);
		return -EIO;
	}

	todo_size = size;

	while (todo_size) {
		struct j1939_sk_buff_cb *skcb;

		segment_size = min_t(size_t, J1939_MAX_TP_PACKET_SIZE,
				     todo_size);

		/* Allocate skb for one segment */
		skb = j1939_sk_alloc_skb(priv->ndev, sk, msg, segment_size,
					 &ret);
		if (ret)
			break;

		skcb = j1939_skb_to_cb(skb);

		if (!session) {
			/* at this point the size should be full size
			 * of the session
			 */
			skcb->offset = 0;
			session = j1939_tp_send(priv, skb, size);
			if (IS_ERR(session)) {
				ret = PTR_ERR(session);
				goto kfree_skb;
			}
			if (j1939_sk_queue_session(session)) {
				/* try to activate session if we a
				 * fist in the queue
				 */
				if (!j1939_session_activate(session)) {
					j1939_tp_schedule_txtimer(session, 0);
				} else {
					ret = -EBUSY;
					session->err = ret;
					j1939_sk_queue_drop_all(priv, jsk,
								EBUSY);
					break;
				}
			}
		} else {
			skcb->offset = session->total_queued_size;
			j1939_session_skb_queue(session, skb);
		}

		todo_size -= segment_size;
		session->total_queued_size += segment_size;
	}

	switch (ret) {
	case 0: /* OK */
		if (todo_size)
			netdev_warn(priv->ndev,
				    "no error found and not completely queued?! %zu\n",
				    todo_size);
		ret = size;
		break;
	case -ERESTARTSYS:
		ret = -EINTR;
		/* fall through */
	case -EAGAIN: /* OK */
		if (todo_size != size)
			ret = size - todo_size;
		break;
	default: /* ERROR */
		break;
	}

	if (session)
		j1939_session_put(session);

	return ret;

 kfree_skb:
	kfree_skb(skb);
	return ret;
}

static int j1939_sk_sendmsg(struct socket *sock, struct msghdr *msg,
			    size_t size)
{
	struct sock *sk = sock->sk;
	struct j1939_sock *jsk = j1939_sk(sk);
	struct j1939_priv *priv;
	int ifindex;
	int ret;

	lock_sock(sock->sk);
	/* various socket state tests */
	if (!(jsk->state & J1939_SOCK_BOUND)) {
		ret = -EBADFD;
		goto sendmsg_done;
	}

	priv = jsk->priv;
	ifindex = jsk->ifindex;

	if (!jsk->addr.src_name && jsk->addr.sa == J1939_NO_ADDR) {
		/* no source address assigned yet */
		ret = -EBADFD;
		goto sendmsg_done;
	}

	/* deal with provided destination address info */
	if (msg->msg_name) {
		struct sockaddr_can *addr = msg->msg_name;

		if (msg->msg_namelen < J1939_MIN_NAMELEN) {
			ret = -EINVAL;
			goto sendmsg_done;
		}

		if (addr->can_family != AF_CAN) {
			ret = -EINVAL;
			goto sendmsg_done;
		}

		if (addr->can_ifindex && addr->can_ifindex != ifindex) {
			ret = -EBADFD;
			goto sendmsg_done;
		}

		if (j1939_pgn_is_valid(addr->can_addr.j1939.pgn) &&
		    !j1939_pgn_is_clean_pdu(addr->can_addr.j1939.pgn)) {
			ret = -EINVAL;
			goto sendmsg_done;
		}

		if (!addr->can_addr.j1939.name &&
		    addr->can_addr.j1939.addr == J1939_NO_ADDR &&
		    !sock_flag(sk, SOCK_BROADCAST)) {
			/* broadcast, but SO_BROADCAST not set */
			ret = -EACCES;
			goto sendmsg_done;
		}
	} else {
		if (!jsk->addr.dst_name && jsk->addr.da == J1939_NO_ADDR &&
		    !sock_flag(sk, SOCK_BROADCAST)) {
			/* broadcast, but SO_BROADCAST not set */
			ret = -EACCES;
			goto sendmsg_done;
		}
	}

	ret = j1939_sk_send_loop(priv, sk, msg, size);

sendmsg_done:
	release_sock(sock->sk);

	return ret;
}

void j1939_sk_netdev_event_netdown(struct j1939_priv *priv)
{
	struct j1939_sock *jsk;
	int error_code = ENETDOWN;

	spin_lock_bh(&priv->j1939_socks_lock);
	list_for_each_entry(jsk, &priv->j1939_socks, list) {
		jsk->sk.sk_err = error_code;
		if (!sock_flag(&jsk->sk, SOCK_DEAD))
			jsk->sk.sk_error_report(&jsk->sk);

		j1939_sk_queue_drop_all(priv, jsk, error_code);
	}
	spin_unlock_bh(&priv->j1939_socks_lock);
}

static int j1939_sk_no_ioctlcmd(struct socket *sock, unsigned int cmd,
				unsigned long arg)
{
	/* no ioctls for socket layer -> hand it down to NIC layer */
	return -ENOIOCTLCMD;
}

static const struct proto_ops j1939_ops = {
	.family = PF_CAN,
	.release = j1939_sk_release,
	.bind = j1939_sk_bind,
	.connect = j1939_sk_connect,
	.socketpair = sock_no_socketpair,
	.accept = sock_no_accept,
	.getname = j1939_sk_getname,
	.poll = datagram_poll,
	.ioctl = j1939_sk_no_ioctlcmd,
	.listen = sock_no_listen,
	.shutdown = sock_no_shutdown,
	.setsockopt = j1939_sk_setsockopt,
	.getsockopt = j1939_sk_getsockopt,
	.sendmsg = j1939_sk_sendmsg,
	.recvmsg = j1939_sk_recvmsg,
	.mmap = sock_no_mmap,
	.sendpage = sock_no_sendpage,
};

static struct proto j1939_proto __read_mostly = {
	.name = "CAN_J1939",
	.owner = THIS_MODULE,
	.obj_size = sizeof(struct j1939_sock),
	.init = j1939_sk_init,
};

const struct can_proto j1939_can_proto = {
	.type = SOCK_DGRAM,
	.protocol = CAN_J1939,
	.ops = &j1939_ops,
	.prot = &j1939_proto,
};