xfrm: use gre key as flow upper protocol info

The GRE Key field is intended to be used for identifying an individual
traffic flow within a tunnel. It is useful to be able to have XFRM
policy selector matches to have different policies for different
GRE tunnels.

Signed-off-by: Timo Teräs <timo.teras@iki.fi>
Signed-off-by: David S. Miller <davem@davemloft.net>
diff --git a/net/ipv4/ip_gre.c b/net/ipv4/ip_gre.c
index cab2057..aace653 100644
--- a/net/ipv4/ip_gre.c
+++ b/net/ipv4/ip_gre.c
@@ -779,9 +779,9 @@
 					.tos = RT_TOS(tos)
 				}
 			},
-			.proto = IPPROTO_GRE
-		}
-;
+			.proto = IPPROTO_GRE,
+			.fl_gre_key = tunnel->parms.o_key
+		};
 		if (ip_route_output_key(dev_net(dev), &rt, &fl)) {
 			dev->stats.tx_carrier_errors++;
 			goto tx_error;
@@ -958,7 +958,8 @@
 					.tos = RT_TOS(iph->tos)
 				}
 			},
-			.proto = IPPROTO_GRE
+			.proto = IPPROTO_GRE,
+			.fl_gre_key = tunnel->parms.o_key
 		};
 		struct rtable *rt;
 
@@ -1223,7 +1224,8 @@
 					.tos = RT_TOS(t->parms.iph.tos)
 				}
 			},
-			.proto = IPPROTO_GRE
+			.proto = IPPROTO_GRE,
+			.fl_gre_key = t->parms.o_key
 		};
 		struct rtable *rt;
 
diff --git a/net/ipv4/xfrm4_policy.c b/net/ipv4/xfrm4_policy.c
index dd1fd8c..4a8c533 100644
--- a/net/ipv4/xfrm4_policy.c
+++ b/net/ipv4/xfrm4_policy.c
@@ -11,6 +11,7 @@
 #include <linux/err.h>
 #include <linux/kernel.h>
 #include <linux/inetdevice.h>
+#include <linux/if_tunnel.h>
 #include <net/dst.h>
 #include <net/xfrm.h>
 #include <net/ip.h>
@@ -154,6 +155,20 @@
 				fl->fl_ipsec_spi = htonl(ntohs(ipcomp_hdr[1]));
 			}
 			break;
+
+		case IPPROTO_GRE:
+			if (pskb_may_pull(skb, xprth + 12 - skb->data)) {
+				__be16 *greflags = (__be16 *)xprth;
+				__be32 *gre_hdr = (__be32 *)xprth;
+
+				if (greflags[0] & GRE_KEY) {
+					if (greflags[0] & GRE_CSUM)
+						gre_hdr++;
+					fl->fl_gre_key = gre_hdr[1];
+				}
+			}
+			break;
+
 		default:
 			fl->fl_ipsec_spi = 0;
 			break;