summaryrefslogtreecommitdiff
path: root/sys/netinet6/nd6_rtr.c
blob: 6ca25f0052705f480cf629b19311a23167959b43 (plain)
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
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
/*	$OpenBSD: nd6_rtr.c,v 1.143 2016/09/02 09:31:25 florian Exp $	*/
/*	$KAME: nd6_rtr.c,v 1.97 2001/02/07 11:09:13 itojun Exp $	*/

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/timeout.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/time.h>
#include <sys/kernel.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/syslog.h>
#include <sys/queue.h>

#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_var.h>
#include <net/route.h>
#include <net/rtable.h>

#include <netinet/in.h>
#include <netinet6/in6_var.h>
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet6/nd6.h>
#include <netinet/icmp6.h>

int rtpref(struct nd_defrouter *);
struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
struct in6_ifaddr *in6_ifadd(struct nd_prefix *, int);
struct nd_pfxrouter *pfxrtr_lookup(struct nd_prefix *, struct nd_defrouter *);
void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
void pfxrtr_del(struct nd_pfxrouter *);
struct nd_pfxrouter *find_pfxlist_reachable_router(struct nd_prefix *);
void defrouter_delreq(struct nd_defrouter *);
void purge_detached(struct ifnet *);
int nd6_prefix_onlink(struct nd_prefix *);
int nd6_prefix_offlink(struct nd_prefix *);
void in6_init_address_ltimes(struct nd_prefix *, struct in6_addrlifetime *);

int rt6_deleteroute(struct rtentry *, void *, unsigned int);

void nd6_addr_add(void *);

void nd6_rs_output_timo(void *);
void nd6_rs_output_set_timo(int);
void nd6_rs_output(struct ifnet *, struct in6_ifaddr *);
void nd6_rs_dev_state(void *);

extern int nd6_recalc_reachtm_interval;

#define ND6_RS_OUTPUT_INTERVAL		60
#define ND6_RS_OUTPUT_QUICK_INTERVAL	1

struct timeout	nd6_rs_output_timer;
int		nd6_rs_output_timeout = ND6_RS_OUTPUT_INTERVAL;
int		nd6_rs_timeout_count = 0;

void
nd6_rs_init(void)
{
	timeout_set(&nd6_rs_output_timer, nd6_rs_output_timo, NULL);
}


/*
 * Receive Router Solicitation Message - just for routers.
 * Router solicitation/advertisement is mostly managed by userland program
 * (rtadvd) so here we have no function like nd6_ra_output().
 *
 * Based on RFC 2461
 */
void
nd6_rs_input(struct mbuf *m, int off, int icmp6len)
{
	struct ifnet *ifp;
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct nd_router_solicit *nd_rs;
	struct in6_addr saddr6 = ip6->ip6_src;
#if 0
	struct in6_addr daddr6 = ip6->ip6_dst;
#endif
	char *lladdr = NULL;
	int lladdrlen = 0;
#if 0
	struct sockaddr_dl *sdl = NULL;
	struct llinfo_nd6 *ln = NULL;
	struct rtentry *rt = NULL;
	int is_newentry;
#endif
	union nd_opts ndopts;
	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];

	/* If I'm not a router, ignore it. XXX - too restrictive? */
	if (!ip6_forwarding)
		goto freeit;

	/* Sanity checks */
	if (ip6->ip6_hlim != 255) {
		nd6log((LOG_ERR,
		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %u\n",
		    ip6->ip6_hlim,
		    inet_ntop(AF_INET6, &ip6->ip6_src, src, sizeof(src)),
		    inet_ntop(AF_INET6, &ip6->ip6_dst, dst, sizeof(dst)),
		    m->m_pkthdr.ph_ifidx));
		goto bad;
	}

	/*
	 * Don't update the neighbor cache, if src = ::.
	 * This indicates that the src has no IP address assigned yet.
	 */
	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
		goto freeit;

	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
	if (nd_rs == NULL) {
		icmp6stat.icp6s_tooshort++;
		return;
	}

	icmp6len -= sizeof(*nd_rs);
	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
	if (nd6_options(&ndopts) < 0) {
		nd6log((LOG_INFO,
		    "nd6_rs_input: invalid ND option, ignored\n"));
		/* nd6_options have incremented stats */
		goto freeit;
	}

	if (ndopts.nd_opts_src_lladdr) {
		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
	}

	ifp = if_get(m->m_pkthdr.ph_ifidx);
	if (ifp == NULL)
		goto freeit;

	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
		nd6log((LOG_INFO,
		    "nd6_rs_input: lladdrlen mismatch for %s "
		    "(if %d, RS packet %d)\n",
		    inet_ntop(AF_INET6, &saddr6, src, sizeof(src)),
		    ifp->if_addrlen, lladdrlen - 2));
		if_put(ifp);
		goto bad;
	}

	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
	if_put(ifp);

 freeit:
	m_freem(m);
	return;

 bad:
	icmp6stat.icp6s_badrs++;
	m_freem(m);
}

void
nd6_rs_output(struct ifnet* ifp, struct in6_ifaddr *ia6)
{
	struct mbuf *m;
	struct ip6_hdr *ip6;
	struct nd_router_solicit *rs;
	struct ip6_moptions im6o;
	caddr_t mac;
	int icmp6len, maxlen, s;

	KASSERT(ia6 != NULL);
	KASSERT(ifp->if_flags & IFF_RUNNING);
	KASSERT(ifp->if_xflags & IFXF_AUTOCONF6);
	KASSERT(!(ia6->ia6_flags & IN6_IFF_TENTATIVE));

	maxlen = sizeof(*ip6) + sizeof(*rs);
	maxlen += (sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7;

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if (m && max_linkhdr + maxlen >= MHLEN) {
		MCLGET(m, M_DONTWAIT);
		if ((m->m_flags & M_EXT) == 0) {
			m_free(m);
			m = NULL;
		}
	}
	if (m == NULL)
		return;

	m->m_pkthdr.ph_ifidx = 0;
	m->m_pkthdr.ph_rtableid = ifp->if_rdomain;
	m->m_flags |= M_MCAST;
	m->m_pkthdr.csum_flags |= M_ICMP_CSUM_OUT;

	im6o.im6o_ifidx = ifp->if_index;
	im6o.im6o_hlim = 255;
	im6o.im6o_loop = 0;

	icmp6len = sizeof(*rs);
	m->m_pkthdr.len = m->m_len = sizeof(*ip6) + icmp6len;
	m->m_data += max_linkhdr;	/* or MH_ALIGN() equivalent? */

	/* fill neighbor solicitation packet */
	ip6 = mtod(m, struct ip6_hdr *);
	ip6->ip6_flow = 0;
	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
	ip6->ip6_vfc |= IPV6_VERSION;
	/* ip6->ip6_plen will be set later */
	ip6->ip6_nxt = IPPROTO_ICMPV6;
	ip6->ip6_hlim = 255;

	ip6->ip6_dst = in6addr_linklocal_allrouters;

	ip6->ip6_src = ia6->ia_addr.sin6_addr;

	rs = (struct nd_router_solicit *)(ip6 + 1);
	rs->nd_rs_type = ND_ROUTER_SOLICIT;
	rs->nd_rs_code = 0;
	rs->nd_rs_cksum = 0;
	rs->nd_rs_reserved = 0;

	if ((mac = nd6_ifptomac(ifp))) {
		int optlen = sizeof(struct nd_opt_hdr) + ifp->if_addrlen;
		struct nd_opt_hdr *nd_opt = (struct nd_opt_hdr *)(rs + 1);
		/* 8 byte alignments... */
		optlen = (optlen + 7) & ~7;

		m->m_pkthdr.len += optlen;
		m->m_len += optlen;
		icmp6len += optlen;
		bzero((caddr_t)nd_opt, optlen);
		nd_opt->nd_opt_type = ND_OPT_SOURCE_LINKADDR;
		nd_opt->nd_opt_len = optlen >> 3;
		bcopy(mac, (caddr_t)(nd_opt + 1), ifp->if_addrlen);
	}

	ip6->ip6_plen = htons((u_short)icmp6len);

	s = splsoftnet();
	ip6_output(m, NULL, NULL, 0, &im6o, NULL);
	splx(s);

	icmp6stat.icp6s_outhist[ND_ROUTER_SOLICIT]++;
}

void
nd6_rs_output_set_timo(int timeout)
{
	nd6_rs_output_timeout = timeout;
	timeout_add_sec(&nd6_rs_output_timer, nd6_rs_output_timeout);
}

void
nd6_rs_output_timo(void *ignored_arg)
{
	struct ifnet *ifp;
	struct in6_ifaddr *ia6;

	if (nd6_rs_timeout_count == 0)
		return;

	if (nd6_rs_output_timeout < ND6_RS_OUTPUT_INTERVAL)
		/* exponential backoff if running quick timeouts */
		nd6_rs_output_timeout *= 2;
	if (nd6_rs_output_timeout > ND6_RS_OUTPUT_INTERVAL)
		nd6_rs_output_timeout = ND6_RS_OUTPUT_INTERVAL;

	TAILQ_FOREACH(ifp, &ifnet, if_list) {
		if (ISSET(ifp->if_flags, IFF_RUNNING) &&
		    ISSET(ifp->if_xflags, IFXF_AUTOCONF6)) {
			ia6 = in6ifa_ifpforlinklocal(ifp, IN6_IFF_TENTATIVE);
			if (ia6 != NULL)
				nd6_rs_output(ifp, ia6);
		}
	}
	nd6_rs_output_set_timo(nd6_rs_output_timeout);
}

void
nd6_rs_attach(struct ifnet *ifp)
{
	if (!ISSET(ifp->if_xflags, IFXF_AUTOCONF6)) {
		/*
		 * We are being called from net/if.c, autoconf is not yet
		 * enabled on the interface.
		 */
		nd6_rs_timeout_count++;
		RS_LHCOOKIE(ifp) = hook_establish(ifp->if_linkstatehooks, 1,
		    nd6_rs_dev_state, ifp);
	}

	/*
	 * (re)send solicitation regardless if we are enableing autoconf
	 * for the first time or if the link comes up
	 */
	nd6_rs_output_set_timo(ND6_RS_OUTPUT_QUICK_INTERVAL);
}

void
nd6_rs_detach(struct ifnet *ifp)
{
	if (ISSET(ifp->if_xflags, IFXF_AUTOCONF6)) {
		nd6_rs_timeout_count--;
		hook_disestablish(ifp->if_linkstatehooks, RS_LHCOOKIE(ifp));
	}

	if (nd6_rs_timeout_count == 0)
		timeout_del(&nd6_rs_output_timer);
}

void
nd6_rs_dev_state(void *arg)
{
	struct ifnet *ifp;

	ifp = (struct ifnet *) arg;

	if (LINK_STATE_IS_UP(ifp->if_link_state) &&
	    ifp->if_flags & IFF_RUNNING)
		/* start quick timer, will exponentially back off */
		nd6_rs_output_set_timo(ND6_RS_OUTPUT_QUICK_INTERVAL);
}

/*
 * Receive Router Advertisement Message.
 *
 * Based on RFC 2461
 */
void
nd6_ra_input(struct mbuf *m, int off, int icmp6len)
{
	struct ifnet *ifp;
	struct nd_ifinfo *ndi;
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct nd_router_advert *nd_ra;
	struct in6_addr saddr6 = ip6->ip6_src;
	union nd_opts ndopts;
	struct nd_defrouter *dr;
	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];

	ifp = if_get(m->m_pkthdr.ph_ifidx);
	if (ifp == NULL)
		goto freeit;

	/* We accept RAs only if inet6 autoconf is enabled  */
	if (!(ifp->if_xflags & IFXF_AUTOCONF6))
		goto freeit;

	ndi = ND_IFINFO(ifp);
	if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
		goto freeit;

	if (nd6_rs_output_timeout != ND6_RS_OUTPUT_INTERVAL)
		/* we saw a RA, stop quick timer */
		nd6_rs_output_set_timo(ND6_RS_OUTPUT_INTERVAL);

	if (ip6->ip6_hlim != 255) {
		nd6log((LOG_ERR,
		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
		    ip6->ip6_hlim,
		    inet_ntop(AF_INET6, &ip6->ip6_src, src, sizeof(src)),
		    inet_ntop(AF_INET6, &ip6->ip6_dst, dst, sizeof(dst)),
		    ifp->if_xname));
		goto bad;
	}

	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
		nd6log((LOG_ERR,
		    "nd6_ra_input: src %s is not link-local\n",
		    inet_ntop(AF_INET6, &saddr6, src, sizeof(src))));
		goto bad;
	}

	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
	if (nd_ra == NULL) {
		icmp6stat.icp6s_tooshort++;
		if_put(ifp);
		return;
	}

	icmp6len -= sizeof(*nd_ra);
	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
	if (nd6_options(&ndopts) < 0) {
		nd6log((LOG_INFO,
		    "nd6_ra_input: invalid ND option, ignored\n"));
		/* nd6_options have incremented stats */
		goto freeit;
	}

    {
	struct nd_defrouter dr0;
	u_int32_t advreachable = nd_ra->nd_ra_reachable;

	memset(&dr0, 0, sizeof(dr0));
	dr0.rtaddr = saddr6;
	dr0.flags  = nd_ra->nd_ra_flags_reserved;
	dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
	dr0.expire = time_second + dr0.rtlifetime;
	dr0.ifp = ifp;
	/* unspecified or not? (RFC 2461 6.3.4) */
	if (advreachable) {
		advreachable = ntohl(advreachable);
		if (advreachable <= MAX_REACHABLE_TIME &&
		    ndi->basereachable != advreachable) {
			ndi->basereachable = advreachable;
			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
		}
	}
	if (nd_ra->nd_ra_retransmit)
		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
	if (nd_ra->nd_ra_curhoplimit) {
		/*
		 * Ignore it.  The router doesn't know the diameter of
		 * the Internet better than this source code.
		 */
	}
	dr = defrtrlist_update(&dr0);
    }

	/*
	 * prefix
	 */
	if (ndopts.nd_opts_pi) {
		struct nd_opt_hdr *pt;
		struct nd_opt_prefix_info *pi = NULL;
		struct nd_prefix pr;

		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
						(pt->nd_opt_len << 3))) {
			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
				continue;
			pi = (struct nd_opt_prefix_info *)pt;

			if (pi->nd_opt_pi_len != 4) {
				nd6log((LOG_INFO,
				    "nd6_ra_input: invalid option "
				    "len %d for prefix information option, "
				    "ignored\n", pi->nd_opt_pi_len));
				continue;
			}

			if (128 < pi->nd_opt_pi_prefix_len) {
				nd6log((LOG_INFO,
				    "nd6_ra_input: invalid prefix "
				    "len %d for prefix information option, "
				    "ignored\n", pi->nd_opt_pi_prefix_len));
				continue;
			}

			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
				nd6log((LOG_INFO,
				    "nd6_ra_input: invalid prefix "
				    "%s, ignored\n",
				    inet_ntop(AF_INET6, &pi->nd_opt_pi_prefix,
					src, sizeof(src))));
				continue;
			}

			/* aggregatable unicast address, rfc2374 */
			if ((pi->nd_opt_pi_prefix.s6_addr8[0] & 0xe0) == 0x20
			 && pi->nd_opt_pi_prefix_len != 64) {
				nd6log((LOG_INFO,
				    "nd6_ra_input: invalid prefixlen "
				    "%d for rfc2374 prefix %s, ignored\n",
				    pi->nd_opt_pi_prefix_len,
				    inet_ntop(AF_INET6, &pi->nd_opt_pi_prefix,
					src, sizeof(src))));
				continue;
			}

			bzero(&pr, sizeof(pr));
			pr.ndpr_prefix.sin6_family = AF_INET6;
			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
			pr.ndpr_ifp = ifp;

			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
			     ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
			     ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
			pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
			pr.ndpr_lastupdate = time_second;

			if (in6_init_prefix_ltimes(&pr))
				continue; /* prefix lifetime init failed */

			(void)prelist_update(&pr, dr, m);
		}
	}

	/*
	 * Source link layer address
	 */
    {
	char *lladdr = NULL;
	int lladdrlen = 0;

	if (ndopts.nd_opts_src_lladdr) {
		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
	}

	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
		nd6log((LOG_INFO,
		    "nd6_ra_input: lladdrlen mismatch for %s "
		    "(if %d, RA packet %d)\n",
		    inet_ntop(AF_INET6, &saddr6, src, sizeof(src)),
		    ifp->if_addrlen, lladdrlen - 2));
		goto bad;
	}

	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);

	/*
	 * Installing a link-layer address might change the state of the
	 * router's neighbor cache, which might also affect our on-link
	 * detection of advertised prefixes.
	 */
	pfxlist_onlink_check();
    }

 freeit:
	if_put(ifp);
	m_freem(m);
	return;

 bad:
	icmp6stat.icp6s_badra++;
	if_put(ifp);
	m_freem(m);
}

/*
 * default router list processing sub routines
 */
void
defrouter_addreq(struct nd_defrouter *new)
{
	struct rt_addrinfo info;
	struct sockaddr_in6 def, mask, gate;
	struct rtentry *rt;
	int s;
	int error;

	memset(&def, 0, sizeof(def));
	memset(&mask, 0, sizeof(mask));
	memset(&gate, 0, sizeof(gate)); /* for safety */
	memset(&info, 0, sizeof(info));

	def.sin6_len = mask.sin6_len = gate.sin6_len =
	    sizeof(struct sockaddr_in6);
	def.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
	gate.sin6_addr = new->rtaddr;
	gate.sin6_scope_id = 0;	/* XXX */

	info.rti_flags = RTF_GATEWAY;
	info.rti_info[RTAX_DST] = sin6tosa(&def);
	info.rti_info[RTAX_GATEWAY] = sin6tosa(&gate);
	info.rti_info[RTAX_NETMASK] = sin6tosa(&mask);

	s = splsoftnet();
	error = rtrequest(RTM_ADD, &info, RTP_DEFAULT, &rt,
	    new->ifp->if_rdomain);
	if (error == 0) {
		rt_sendmsg(rt, RTM_ADD, new->ifp->if_rdomain);
		rtfree(rt);
		new->installed = 1;
	}
	splx(s);
	return;
}

struct nd_defrouter *
defrouter_lookup(struct in6_addr *addr, unsigned int ifidx)
{
	struct nd_defrouter *dr;

	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry)
		if (dr->ifp->if_index == ifidx &&
		    IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
			return (dr);

	return (NULL);		/* search failed */
}

void
defrtrlist_del(struct nd_defrouter *dr)
{
	struct nd_defrouter *deldr = NULL;
	struct in6_ifextra *ext = dr->ifp->if_afdata[AF_INET6];
	struct nd_prefix *pr;

	/*
	 * Flush all the routing table entries that use the router
	 * as a next hop.
	 */
	/* XXX: better condition? */
	if (!ip6_forwarding)
		rt6_flush(&dr->rtaddr, dr->ifp);

	if (dr->installed) {
		deldr = dr;
		defrouter_delreq(dr);
	}
	TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);

	/*
	 * Also delete all the pointers to the router in each prefix lists.
	 */
	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
		struct nd_pfxrouter *pfxrtr;
		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
			pfxrtr_del(pfxrtr);
	}
	pfxlist_onlink_check();

	/*
	 * If the router is the primary one, choose a new one.
	 * Note that defrouter_select() will remove the current gateway
	 * from the routing table.
	 */
	if (deldr)
		defrouter_select();

	ext->ndefrouters--;
	if (ext->ndefrouters < 0) {
		log(LOG_WARNING, "defrtrlist_del: negative count on %s\n",
		    dr->ifp->if_xname);
	}

	free(dr, M_IP6NDP, sizeof(*dr));
}

/*
 * Remove the default route for a given router.
 * This is just a subroutine function for defrouter_select(), and should
 * not be called from anywhere else.
 */
void
defrouter_delreq(struct nd_defrouter *dr)
{
	struct rt_addrinfo info;
	struct sockaddr_in6 def, mask, gw;
	struct rtentry *rt;
	int error;

#ifdef DIAGNOSTIC
	if (!dr)
		panic("dr == NULL in defrouter_delreq");
#endif

	memset(&info, 0, sizeof(info));
	memset(&def, 0, sizeof(def));
	memset(&mask, 0, sizeof(mask));
	memset(&gw, 0, sizeof(gw));	/* for safety */

	def.sin6_len = mask.sin6_len = gw.sin6_len =
	    sizeof(struct sockaddr_in6);
	def.sin6_family = mask.sin6_family = gw.sin6_family = AF_INET6;
	gw.sin6_addr = dr->rtaddr;
	gw.sin6_scope_id = 0;	/* XXX */

	info.rti_flags = RTF_GATEWAY;
	info.rti_info[RTAX_DST] = sin6tosa(&def);
	info.rti_info[RTAX_GATEWAY] = sin6tosa(&gw);
	info.rti_info[RTAX_NETMASK] = sin6tosa(&mask);

	error = rtrequest(RTM_DELETE, &info, RTP_DEFAULT, &rt,
	    dr->ifp->if_rdomain);
	if (error == 0) {
		rt_sendmsg(rt, RTM_DELETE, dr->ifp->if_rdomain);
		rtfree(rt);
	}

	dr->installed = 0;
}

/*
 * remove all default routes from default router list
 */
void
defrouter_reset(void)
{
	struct nd_defrouter *dr;

	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry)
		defrouter_delreq(dr);

	/*
	 * XXX should we also nuke any default routers in the kernel, by
	 * going through them by rtalloc()?
	 */
}

/*
 * Default Router Selection according to Section 6.3.6 of RFC 2461 and
 * draft-ietf-ipngwg-router-selection:
 * 1) Routers that are reachable or probably reachable should be preferred.
 *    If we have more than one (probably) reachable router, prefer ones
 *    with the highest router preference.
 * 2) When no routers on the list are known to be reachable or
 *    probably reachable, routers SHOULD be selected in a round-robin
 *    fashion, regardless of router preference values.
 * 3) If the Default Router List is empty, assume that all
 *    destinations are on-link.
 *
 * We assume nd_defrouter is sorted by router preference value.
 * Since the code below covers both with and without router preference cases,
 * we do not need to classify the cases by ifdef.
 *
 * At this moment, we do not try to install more than one default router,
 * even when the multipath routing is available, because we're not sure about
 * the benefits for stub hosts comparing to the risk of making the code
 * complicated and the possibility of introducing bugs.
 */
void
defrouter_select(void)
{
	struct nd_defrouter *dr, *selected_dr = NULL, *installed_dr = NULL;
	struct rtentry *rt = NULL;
	struct llinfo_nd6 *ln = NULL;
	int s = splsoftnet();

	/*
	 * Let's handle easy case (3) first:
	 * If default router list is empty, there's nothing to be done.
	 */
	if (TAILQ_EMPTY(&nd_defrouter)) {
		splx(s);
		return;
	}

	/*
	 * Search for a (probably) reachable router from the list.
	 * We just pick up the first reachable one (if any), assuming that
	 * the ordering rule of the list described in defrtrlist_update().
	 */
	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry) {
		if (!(dr->ifp->if_xflags & IFXF_AUTOCONF6))
			continue;
		if (!selected_dr) {
			rt = nd6_lookup(&dr->rtaddr, 0, dr->ifp,
			    dr->ifp->if_rdomain);
			if ((rt != NULL) &&
			    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
			    ND6_IS_LLINFO_PROBREACH(ln)) {
				selected_dr = dr;
			}
			rtfree(rt);
		}

		if (dr->installed && !installed_dr)
			installed_dr = dr;
		else if (dr->installed && installed_dr) {
			/* this should not happen.  warn for diagnosis. */
			log(LOG_ERR, "defrouter_select: more than one router"
			    " is installed\n");
		}
	}
	/*
	 * If none of the default routers was found to be reachable,
	 * round-robin the list regardless of preference.
	 * Otherwise, if we have an installed router, check if the selected
	 * (reachable) router should really be preferred to the installed one.
	 * We only prefer the new router when the old one is not reachable
	 * or when the new one has a really higher preference value.
	 */
	if (!selected_dr) {
		if (!installed_dr || !TAILQ_NEXT(installed_dr, dr_entry))
			selected_dr = TAILQ_FIRST(&nd_defrouter);
		else
			selected_dr = TAILQ_NEXT(installed_dr, dr_entry);
	} else if (installed_dr) {
		rt = nd6_lookup(&installed_dr->rtaddr, 0, installed_dr->ifp,
		    installed_dr->ifp->if_rdomain);
		if ((rt != NULL) && (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
		    ND6_IS_LLINFO_PROBREACH(ln) &&
		    rtpref(selected_dr) <= rtpref(installed_dr)) {
			selected_dr = installed_dr;
		}
		rtfree(rt);
	}

	/*
	 * If the selected router is different than the installed one,
	 * remove the installed router and install the selected one.
	 * Note that the selected router is never NULL here.
	 */
	if (installed_dr != selected_dr) {
		if (installed_dr)
			defrouter_delreq(installed_dr);
		defrouter_addreq(selected_dr);
	}

	splx(s);
	return;
}

/*
 * for default router selection
 * regards router-preference field as a 2-bit signed integer
 */
int
rtpref(struct nd_defrouter *dr)
{
#ifdef RTPREF
	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
	case ND_RA_FLAG_RTPREF_HIGH:
		return RTPREF_HIGH;
	case ND_RA_FLAG_RTPREF_MEDIUM:
	case ND_RA_FLAG_RTPREF_RSV:
		return RTPREF_MEDIUM;
	case ND_RA_FLAG_RTPREF_LOW:
		return RTPREF_LOW;
	default:
		/*
		 * This case should never happen.  If it did, it would mean a
		 * serious bug of kernel internal.  We thus always bark here.
		 * Or, can we even panic?
		 */
		log(LOG_ERR, "rtpref: impossible RA flag %x", dr->flags);
		return RTPREF_INVALID;
	}
	/* NOTREACHED */
#else
	return 0;
#endif
}

struct nd_defrouter *
defrtrlist_update(struct nd_defrouter *new)
{
	struct nd_defrouter *dr, *n;
	struct in6_ifextra *ext = new->ifp->if_afdata[AF_INET6];
	int s = splsoftnet();

	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp->if_index)) != NULL) {
		/* entry exists */
		if (new->rtlifetime == 0) {
			defrtrlist_del(dr);
			dr = NULL;
		} else {
			int oldpref = rtpref(dr);

			/* override */
			dr->flags = new->flags; /* xxx flag check */
			dr->rtlifetime = new->rtlifetime;
			dr->expire = new->expire;

			if (!dr->installed)
				defrouter_select();

			/*
			 * If the preference does not change, there's no need
			 * to sort the entries.
			 */
			if (rtpref(new) == oldpref) {
				splx(s);
				return (dr);
			}

			/*
			 * preferred router may be changed, so relocate
			 * this router.
			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
			 * However, since defrtrlist_del() has many side
			 * effects, we intentionally do so here.
			 * defrouter_select() below will handle routing
			 * changes later.
			 */
			TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
			n = dr;
			goto insert;
		}
		splx(s);
		return (dr);
	}

	/* entry does not exist */
	if (new->rtlifetime == 0) {
		/* flush all possible redirects */
		if (new->ifp->if_xflags & IFXF_AUTOCONF6)
			rt6_flush(&new->rtaddr, new->ifp);
		splx(s);
		return (NULL);
	}

	if (ip6_maxifdefrouters >= 0 &&
	    ext->ndefrouters >= ip6_maxifdefrouters) {
		splx(s);
		return (NULL);
	}

	n = malloc(sizeof(*n), M_IP6NDP, M_NOWAIT | M_ZERO);
	if (n == NULL) {
		splx(s);
		return (NULL);
	}
	*n = *new;

insert:
	/*
	 * Insert the new router in the Default Router List;
	 * The Default Router List should be in the descending order
	 * of router-preference.  Routers with the same preference are
	 * sorted in the arriving time order.
	 */

	/* insert at the end of the group */
	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry)
		if (rtpref(n) > rtpref(dr))
			break;
	if (dr)
		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
	else
		TAILQ_INSERT_TAIL(&nd_defrouter, n, dr_entry);

	defrouter_select();

	ext->ndefrouters++;

	splx(s);

	return (n);
}

struct nd_pfxrouter *
pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
{
	struct nd_pfxrouter *search;

	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
		if (search->router == dr)
			break;
	}

	return (search);
}

void
pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
{
	struct nd_pfxrouter *new;

	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
	if (new == NULL)
		return;
	new->router = dr;

	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);

	pfxlist_onlink_check();
}

void
pfxrtr_del(struct nd_pfxrouter *pfr)
{
	LIST_REMOVE(pfr, pfr_entry);
	free(pfr, M_IP6NDP, sizeof(*pfr));
}

struct nd_prefix *
nd6_prefix_lookup(struct nd_prefix *pr)
{
	struct nd_prefix *search;

	LIST_FOREACH(search, &nd_prefix, ndpr_entry) {
		if (pr->ndpr_ifp == search->ndpr_ifp &&
		    pr->ndpr_plen == search->ndpr_plen &&
		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
		    &search->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
			break;
		}
	}

	return (search);
}

void
purge_detached(struct ifnet *ifp)
{
	struct nd_prefix *pr, *pr_next;
	struct in6_ifaddr *ia6;
	struct ifaddr *ifa, *ifa_next;

	splsoftassert(IPL_SOFTNET);

	LIST_FOREACH_SAFE(pr, &nd_prefix, ndpr_entry, pr_next) {
		/*
		 * This function is called when we need to make more room for
		 * new prefixes rather than keeping old, possibly stale ones.
		 * Detached prefixes would be a good candidate; if all routers
		 * that advertised the prefix expired, the prefix is also
		 * probably stale.
		 */
		if (pr->ndpr_ifp != ifp ||
		    IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
		    ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
		    !LIST_EMPTY(&pr->ndpr_advrtrs)))
			continue;

		TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrlist, ifa_list, ifa_next) {
			if (ifa->ifa_addr->sa_family != AF_INET6)
				continue;
			ia6 = ifatoia6(ifa);
			if ((ia6->ia6_flags & IN6_IFF_AUTOCONF) ==
			    IN6_IFF_AUTOCONF && ia6->ia6_ndpr == pr) {
				in6_purgeaddr(ifa);
			}
		}
	}
}

int
nd6_prelist_add(struct nd_prefix *pr, struct nd_defrouter *dr,
    struct nd_prefix **newp)
{
	struct nd_prefix *new = NULL;
	int i, s;
	struct in6_ifextra *ext = pr->ndpr_ifp->if_afdata[AF_INET6];

	if (ip6_maxifprefixes >= 0) {
		if (ext->nprefixes >= ip6_maxifprefixes / 2) {
			s = splsoftnet();
			purge_detached(pr->ndpr_ifp);
			splx(s);
		}
		if (ext->nprefixes >= ip6_maxifprefixes)
			return(ENOMEM);
	}

	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
	if (new == NULL)
		return ENOMEM;
	*new = *pr;
	if (newp != NULL)
		*newp = new;

	/* initialization */
	LIST_INIT(&new->ndpr_advrtrs);
	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
	/* make prefix in the canonical form */
	for (i = 0; i < 4; i++)
		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
		    new->ndpr_mask.s6_addr32[i];

	task_set(&new->ndpr_task, nd6_addr_add, new);

	s = splsoftnet();
	/* link ndpr_entry to nd_prefix list */
	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);

	/* ND_OPT_PI_FLAG_ONLINK processing */
	if (new->ndpr_raf_onlink) {
		char addr[INET6_ADDRSTRLEN];
		int e;

		if ((e = nd6_prefix_onlink(new)) != 0) {
			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
			    "the prefix %s/%d on-link on %s (errno=%d)\n",
			    inet_ntop(AF_INET6, &pr->ndpr_prefix.sin6_addr,
				addr, sizeof(addr)),
			    pr->ndpr_plen, pr->ndpr_ifp->if_xname, e));
			/* proceed anyway. XXX: is it correct? */
		}
	}

	if (dr)
		pfxrtr_add(new, dr);
	splx(s);

	ext->nprefixes++;

	return 0;
}

void
prelist_remove(struct nd_prefix *pr)
{
	struct nd_pfxrouter *pfr, *next;
	int e, s;
	struct in6_ifextra *ext = pr->ndpr_ifp->if_afdata[AF_INET6];

	/* make sure to invalidate the prefix until it is really freed. */
	pr->ndpr_vltime = 0;
	pr->ndpr_pltime = 0;

	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
	    (e = nd6_prefix_offlink(pr)) != 0) {
		char addr[INET6_ADDRSTRLEN];
		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
		    "on %s, errno=%d\n",
		    inet_ntop(AF_INET6, &pr->ndpr_prefix.sin6_addr,
			addr, sizeof(addr)),
		    pr->ndpr_plen, pr->ndpr_ifp->if_xname, e));
		/* what should we do? */
	}

	if (pr->ndpr_refcnt > 0)
		return;		/* notice here? */

	s = splsoftnet();

	/* unlink ndpr_entry from nd_prefix list */
	LIST_REMOVE(pr, ndpr_entry);

	/* free list of routers that adversed the prefix */
	LIST_FOREACH_SAFE(pfr, &pr->ndpr_advrtrs, pfr_entry, next)
		free(pfr, M_IP6NDP, sizeof(*pfr));

	ext->nprefixes--;
	if (ext->nprefixes < 0) {
		log(LOG_WARNING, "prelist_remove: negative count on %s\n",
		    pr->ndpr_ifp->if_xname);
	}

	free(pr, M_IP6NDP, sizeof(*pr));

	pfxlist_onlink_check();
	splx(s);
}

/*
 * dr - may be NULL
 */

int
prelist_update(struct nd_prefix *new, struct nd_defrouter *dr, struct mbuf *m)
{
	struct in6_ifaddr *ia6_match = NULL;
	struct ifaddr *ifa;
	struct ifnet *ifp = new->ndpr_ifp;
	struct nd_prefix *pr;
	int s, error = 0;
	int tempaddr_preferred = 0, autoconf = 0, statique = 0;
	int auth;
	struct in6_addrlifetime lt6_tmp;
	char addr[INET6_ADDRSTRLEN];

	s = splsoftnet();

	auth = 0;
	if (m) {
		/*
		 * Authenticity for NA consists authentication for
		 * both IP header and IP datagrams, doesn't it ?
		 */
		auth = (m->m_flags & M_AUTH);
	}

	if ((pr = nd6_prefix_lookup(new)) != NULL) {
		/*
		 * nd6_prefix_lookup() ensures that pr and new have the same
		 * prefix on a same interface.
		 */

		/*
		 * Update prefix information.  Note that the on-link (L) bit
		 * and the autonomous (A) bit should NOT be changed from 1
		 * to 0.
		 */
		if (new->ndpr_raf_onlink == 1)
			pr->ndpr_raf_onlink = 1;
		if (new->ndpr_raf_auto == 1)
			pr->ndpr_raf_auto = 1;
		if (new->ndpr_raf_onlink) {
			pr->ndpr_vltime = new->ndpr_vltime;
			pr->ndpr_pltime = new->ndpr_pltime;
			pr->ndpr_preferred = new->ndpr_preferred;
			pr->ndpr_expire = new->ndpr_expire;
			pr->ndpr_lastupdate = new->ndpr_lastupdate;
		}

		if (new->ndpr_raf_onlink &&
		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
			int e;

			if ((e = nd6_prefix_onlink(pr)) != 0) {
				nd6log((LOG_ERR,
				    "prelist_update: failed to make "
				    "the prefix %s/%d on-link on %s "
				    "(errno=%d)\n",
				    inet_ntop(AF_INET6,
					&pr->ndpr_prefix.sin6_addr,
					addr, sizeof(addr)),
				    pr->ndpr_plen, pr->ndpr_ifp->if_xname, e));
				/* proceed anyway. XXX: is it correct? */
			}
		}

		if (dr && pfxrtr_lookup(pr, dr) == NULL)
			pfxrtr_add(pr, dr);
	} else {
		struct nd_prefix *newpr = NULL;

		if (new->ndpr_vltime == 0)
			goto end;
		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
			goto end;

		error = nd6_prelist_add(new, dr, &newpr);
		if (error != 0 || newpr == NULL) {
			nd6log((LOG_NOTICE, "prelist_update: "
			    "nd6_prelist_add failed for %s/%d on %s "
			    "errno=%d, returnpr=%p\n",
			    inet_ntop(AF_INET6, &new->ndpr_prefix.sin6_addr,
				addr, sizeof(addr)),
			    new->ndpr_plen, new->ndpr_ifp->if_xname,
			    error, newpr));
			goto end; /* we should just give up in this case. */
		}

		pr = newpr;
	}

	/*
	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
	 * Note that pr must be non NULL at this point.
	 */

	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
	if (!new->ndpr_raf_auto)
		goto end;

	/*
	 * 5.5.3 (b). the link-local prefix should have been ignored in
	 * nd6_ra_input.
	 */

	/*
	 * 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime.
	 * This should have been done in nd6_ra_input.
	 */

	/*
	 * 5.5.3 (d). If the prefix advertised does not match the prefix of an
	 * address already in the list, and the Valid Lifetime is not 0,
	 * form an address.  Note that even a manually configured address
	 * should reject autoconfiguration of a new address.
	 */
	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
		struct in6_ifaddr *ia6;
		int ifa_plen;
		u_int32_t storedlifetime;

		if (ifa->ifa_addr->sa_family != AF_INET6)
			continue;

		ia6 = ifatoia6(ifa);

		/*
		 * Spec is not clear here, but I believe we should concentrate
		 * on unicast (i.e. not anycast) addresses.
		 * XXX: other ia6_flags? detached or duplicated?
		 */
		if ((ia6->ia6_flags & IN6_IFF_ANYCAST) != 0)
			continue;

		ifa_plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
		if (ifa_plen != new->ndpr_plen ||
		    !in6_are_prefix_equal(&ia6->ia_addr.sin6_addr,
		    &new->ndpr_prefix.sin6_addr, ifa_plen))
			continue;

		if (ia6_match == NULL) /* remember the first one */
			ia6_match = ia6;

		if ((ia6->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
			statique = 1;
			continue;
		}

		/*
		 * An already autoconfigured address matched.  Now that we
		 * are sure there is at least one matched address, we can
		 * proceed to 5.5.3. (e): update the lifetimes according to the
		 * "two hours" rule and the privacy extension.
		 */
#define TWOHOUR		(120*60)
		/*
		 * RFC2462 introduces the notion of StoredLifetime to the
		 * "two hours" rule as follows:
		 *   the Lifetime associated with the previously autoconfigured
		 *   address.
		 * Our interpretation of this definition is "the remaining
		 * lifetime to expiration at the evaluation time".  One might
		 * be wondering if this interpretation is really conform to the
		 * RFC, because the text can read that "Lifetimes" are never
		 * decreased, and our definition of the "storedlifetime" below
		 * essentially reduces the "Valid Lifetime" advertised in the
		 * previous RA.  But, this is due to the wording of the text,
		 * and our interpretation is the same as an author's intention.
		 * See the discussion in the IETF ipngwg ML in August 2001,
		 * with the Subject "StoredLifetime in RFC 2462".
		 */
		lt6_tmp = ia6->ia6_lifetime;

		/* RFC 4941 temporary addresses (privacy extension). */
		if (ia6->ia6_flags & IN6_IFF_PRIVACY) {
			/* Do we still have a non-deprecated address? */
			if ((ia6->ia6_flags & IN6_IFF_DEPRECATED) == 0)
				tempaddr_preferred = 1;
			/* Don't extend lifetime for temporary addresses. */
			if (new->ndpr_vltime >= lt6_tmp.ia6t_vltime)
				continue;
			if (new->ndpr_pltime >= lt6_tmp.ia6t_pltime)
				continue;
		} else if ((ia6->ia6_flags & IN6_IFF_DEPRECATED) == 0)
			/* We have a regular SLAAC address. */
			autoconf = 1;

		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
			storedlifetime = ND6_INFINITE_LIFETIME;
		else if (time_second - ia6->ia6_updatetime >
			 lt6_tmp.ia6t_vltime) {
			/*
			 * The case of "invalid" address.  We should usually
			 * not see this case.
			 */
			storedlifetime = 0;
		} else
			storedlifetime = lt6_tmp.ia6t_vltime -
				(time_second - ia6->ia6_updatetime);
		if (TWOHOUR < new->ndpr_vltime ||
		    storedlifetime < new->ndpr_vltime) {
			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
		} else if (storedlifetime <= TWOHOUR
#if 0
			   /*
			    * This condition is logically redundant, so we just
			    * omit it.
			    * See IPng 6712, 6717, and 6721.
			    */
			   && new->ndpr_vltime <= storedlifetime
#endif
			) {
			if (auth) {
				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
			}
		} else {
			/*
			 * new->ndpr_vltime <= TWOHOUR &&
			 * TWOHOUR < storedlifetime
			 */
			lt6_tmp.ia6t_vltime = TWOHOUR;
		}

		/* The 2 hour rule is not imposed for preferred lifetime. */
		lt6_tmp.ia6t_pltime = new->ndpr_pltime;

		in6_init_address_ltimes(pr, &lt6_tmp);

		ia6->ia6_lifetime = lt6_tmp;
		ia6->ia6_updatetime = time_second;
	}

	if ((!autoconf || ((ifp->if_xflags & IFXF_INET6_NOPRIVACY) == 0 &&
	     !tempaddr_preferred)) &&
	    new->ndpr_vltime != 0 && new->ndpr_pltime != 0 &&
	    !((ifp->if_xflags & IFXF_INET6_NOPRIVACY) && statique)) {
		/*
		 * There is no SLAAC address and/or there is no preferred RFC
		 * 4941 temporary address. And prefix lifetimes are non-zero.
		 * And there is no static address in the same prefix.
		 * Create new addresses in process context.
		 * Increment prefix refcount to ensure the prefix is not
		 * removed before the task is done.
		 */
		pr->ndpr_refcnt++;
		if (task_add(systq, &pr->ndpr_task) == 0)
			pr->ndpr_refcnt--;
	}

 end:
	splx(s);
	return error;
}

void
nd6_addr_add(void *prptr)
{
	struct nd_prefix *pr = (struct nd_prefix *)prptr;
	struct in6_ifaddr *ia6;
	struct ifaddr *ifa;
	int ifa_plen, autoconf, privacy, s;

	s = splsoftnet();

	autoconf = 1;
	privacy = (pr->ndpr_ifp->if_xflags & IFXF_INET6_NOPRIVACY) == 0;

	/*
	 * Check again if a non-deprecated address has already
	 * been autoconfigured for this prefix.
	 */
	TAILQ_FOREACH(ifa, &pr->ndpr_ifp->if_addrlist, ifa_list) {
		if (ifa->ifa_addr->sa_family != AF_INET6)
			continue;

		ia6 = ifatoia6(ifa);

		/*
		 * Spec is not clear here, but I believe we should concentrate
		 * on unicast (i.e. not anycast) addresses.
		 * XXX: other ia6_flags? detached or duplicated?
		 */
		if ((ia6->ia6_flags & IN6_IFF_ANYCAST) != 0)
			continue;

		if ((ia6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
			continue;

		if ((ia6->ia6_flags & IN6_IFF_DEPRECATED) != 0)
			continue;

		ifa_plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
		if (ifa_plen == pr->ndpr_plen &&
		    in6_are_prefix_equal(&ia6->ia_addr.sin6_addr,
		    &pr->ndpr_prefix.sin6_addr, ifa_plen)) {
			if ((ia6->ia6_flags & IN6_IFF_PRIVACY) == 0)
				autoconf = 0;
			else
				privacy = 0;
			if (!autoconf && !privacy)
				break;
		}
	}

	if (autoconf && (ia6 = in6_ifadd(pr, 0)) != NULL) {
		ia6->ia6_ndpr = pr;
		pr->ndpr_refcnt++;
	} else
		autoconf = 0;

	if (privacy && (ia6 = in6_ifadd(pr, 1)) != NULL) {
		ia6->ia6_ndpr = pr;
		pr->ndpr_refcnt++;
	} else
		privacy = 0;

	/*
	 * A newly added address might affect the status
	 * of other addresses, so we check and update it.
	 * XXX: what if address duplication happens?
	 */
	if (autoconf || privacy)
		pfxlist_onlink_check();

	/* Decrement prefix refcount now that the task is done. */
	if (--pr->ndpr_refcnt == 0)
		prelist_remove(pr);

	splx(s);
}

/*
 * A supplement function used in the on-link detection below;
 * detect if a given prefix has a (probably) reachable advertising router.
 * XXX: lengthy function name...
 */
struct nd_pfxrouter *
find_pfxlist_reachable_router(struct nd_prefix *pr)
{
	struct nd_pfxrouter *pfxrtr;
	struct rtentry *rt = NULL;
	struct llinfo_nd6 *ln;

	LIST_FOREACH(pfxrtr, &pr->ndpr_advrtrs, pfr_entry) {
		if ((rt = nd6_lookup(&pfxrtr->router->rtaddr, 0,
		    pfxrtr->router->ifp, pfxrtr->router->ifp->if_rdomain)) &&
		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
		    ND6_IS_LLINFO_PROBREACH(ln)) {
			rtfree(rt);
			break;	/* found */
		}
		rtfree(rt);
	}

	return (pfxrtr);
}

/*
 * Check if each prefix in the prefix list has at least one available router
 * that advertised the prefix (a router is "available" if its neighbor cache
 * entry is reachable or probably reachable).
 * If the check fails, the prefix may be off-link, because, for example,
 * we have moved from the network but the lifetime of the prefix has not
 * expired yet.  So we should not use the prefix if there is another prefix
 * that has an available router.
 * But, if there is no prefix that has an available router, we still regards
 * all the prefixes as on-link.  This is because we can't tell if all the
 * routers are simply dead or if we really moved from the network and there
 * is no router around us.
 */
void
pfxlist_onlink_check(void)
{
	struct nd_prefix *pr;
	struct in6_ifaddr *ia6;
	char addr[INET6_ADDRSTRLEN];

	/*
	 * Check if there is a prefix that has a reachable advertising
	 * router.
	 */
	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
			break;
	}
	if (pr != NULL || !TAILQ_EMPTY(&nd_defrouter)) {
		/*
		 * There is at least one prefix that has a reachable router,
		 * or at least a router which probably does not advertise
		 * any prefixes.  The latter would be the case when we move
		 * to a new link where we have a router that does not provide
		 * prefixes and we configure an address by hand.
		 * Detach prefixes which have no reachable advertising
		 * router, and attach other prefixes.
		 */
		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
			/* XXX: a link-local prefix should never be detached */
			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
				continue;

			/*
			 * we aren't interested in prefixes without the L bit
			 * set.
			 */
			if (pr->ndpr_raf_onlink == 0)
				continue;

			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
			    find_pfxlist_reachable_router(pr) == NULL)
				pr->ndpr_stateflags |= NDPRF_DETACHED;
			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
			    find_pfxlist_reachable_router(pr) != 0)
				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
		}
	} else {
		/* there is no prefix that has a reachable router */
		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
				continue;

			if (pr->ndpr_raf_onlink == 0)
				continue;

			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
		}
	}

	/*
	 * Remove each interface route associated with a (just) detached
	 * prefix, and reinstall the interface route for a (just) attached
	 * prefix.  Note that all attempt of reinstallation does not
	 * necessarily success, when a same prefix is shared among multiple
	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
	 * so we don't have to care about them.
	 */
	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
		int e;

		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
			continue;

		if (pr->ndpr_raf_onlink == 0)
			continue;

		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
			if ((e = nd6_prefix_offlink(pr)) != 0) {
				nd6log((LOG_ERR,
				    "pfxlist_onlink_check: failed to "
				    "make %s/%d offlink, errno=%d\n",
				    inet_ntop(AF_INET6,
					&pr->ndpr_prefix.sin6_addr,
					addr, sizeof(addr)),
				    pr->ndpr_plen, e));
			}
		}
		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
		    pr->ndpr_raf_onlink) {
			if ((e = nd6_prefix_onlink(pr)) != 0) {
				nd6log((LOG_ERR,
				    "pfxlist_onlink_check: failed to "
				    "make %s/%d offlink, errno=%d\n",
				    inet_ntop(AF_INET6,
					&pr->ndpr_prefix.sin6_addr,
					addr, sizeof(addr)),
				    pr->ndpr_plen, e));
			}
		}
	}

	/*
	 * Changes on the prefix status might affect address status as well.
	 * Make sure that all addresses derived from an attached prefix are
	 * attached, and that all addresses derived from a detached prefix are
	 * detached.  Note, however, that a manually configured address should
	 * always be attached.
	 * The precise detection logic is same as the one for prefixes.
	 */
	TAILQ_FOREACH(ia6, &in6_ifaddr, ia_list) {
		if (!(ia6->ia6_flags & IN6_IFF_AUTOCONF))
			continue;

		if (ia6->ia6_ndpr == NULL) {
			/*
			 * This can happen when we first configure the address
			 * (i.e. the address exists, but the prefix does not).
			 * XXX: complicated relationships...
			 */
			continue;
		}

		if (find_pfxlist_reachable_router(ia6->ia6_ndpr))
			break;
	}
	if (ia6) {
		TAILQ_FOREACH(ia6, &in6_ifaddr, ia_list) {
			if ((ia6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
				continue;

			if (ia6->ia6_ndpr == NULL) /* XXX: see above. */
				continue;

			if (find_pfxlist_reachable_router(ia6->ia6_ndpr))
				ia6->ia6_flags &= ~IN6_IFF_DETACHED;
			else
				ia6->ia6_flags |= IN6_IFF_DETACHED;
		}
	}
	else {
		TAILQ_FOREACH(ia6, &in6_ifaddr, ia_list) {
			if ((ia6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
				continue;

			ia6->ia6_flags &= ~IN6_IFF_DETACHED;
		}
	}
}

int
nd6_prefix_onlink(struct nd_prefix *pr)
{
	struct ifnet *ifp = pr->ndpr_ifp;
	struct ifaddr *ifa;
	struct nd_prefix *opr;
	char addr[INET6_ADDRSTRLEN];
	int error, rtflags = 0;

	/* sanity check */
	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0)
		return (EEXIST);

	/*
	 * Add the interface route associated with the prefix.  Before
	 * installing the route, check if there's the same prefix on another
	 * interface, and the prefix has already installed the interface route.
	 * Although such a configuration is expected to be rare, we explicitly
	 * allow it.
	 */
	LIST_FOREACH(opr, &nd_prefix, ndpr_entry) {
		if (opr == pr)
			continue;

		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
			continue;

		if (opr->ndpr_plen == pr->ndpr_plen &&
		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
			return (0);
	}

	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
		if (ifa->ifa_addr->sa_family != AF_INET6)
			continue;
		if (ifatoia6(ifa)->ia6_ndpr == pr)
			break;
	}
	if (ifa == NULL) {
		/*
		 * This can still happen, when, for example, we receive an RA
		 * containing a prefix with the L bit set and the A bit clear,
		 * after removing all IPv6 addresses on the receiving
		 * interface.  This should, of course, be rare though.
		 */
		nd6log((LOG_NOTICE,
		    "nd6_prefix_onlink: failed to find any ifaddr"
		    " to add route for a prefix(%s/%d) on %s\n",
		    inet_ntop(AF_INET6,	&pr->ndpr_prefix.sin6_addr,
			addr, sizeof(addr)),
		    pr->ndpr_plen, ifp->if_xname));
		return (0);
	}

	if (nd6_need_cache(ifp))
		rtflags = RTF_CLONING | RTF_CONNECTED;

	error = rt_ifa_add(ifa, rtflags, sin6tosa(&pr->ndpr_prefix));
	if (error == 0)
		pr->ndpr_stateflags |= NDPRF_ONLINK;

	return (error);
}

int
nd6_prefix_offlink(struct nd_prefix *pr)
{
	struct ifnet *ifp = pr->ndpr_ifp;
	struct ifaddr *ifa;
	struct nd_prefix *opr;
	char addr[INET6_ADDRSTRLEN];
	int error, rtflags = 0;

	/* sanity check */
	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
		nd6log((LOG_ERR,
		    "nd6_prefix_offlink: %s/%d is already off-link\n",
		    inet_ntop(AF_INET6, &pr->ndpr_prefix.sin6_addr,
			addr, sizeof(addr)),
		    pr->ndpr_plen));
		return (EEXIST);
	}

	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
		if (ifa->ifa_addr->sa_family != AF_INET6)
			continue;
		if (ifatoia6(ifa)->ia6_ndpr == pr)
			break;
	}
	if (ifa == NULL)
		return (EINVAL);

	if (nd6_need_cache(ifp))
		rtflags = RTF_CLONING | RTF_CONNECTED;

	error = rt_ifa_del(ifa, rtflags, sin6tosa(&pr->ndpr_prefix));
	if (error == 0) {
		pr->ndpr_stateflags &= ~NDPRF_ONLINK;

		/*
		 * There might be the same prefix on another interface,
		 * the prefix which could not be on-link just because we have
		 * the interface route (see comments in nd6_prefix_onlink).
		 * If there's one, try to make the prefix on-link on the
		 * interface.
		 */
		LIST_FOREACH(opr, &nd_prefix, ndpr_entry) {
			if (opr == pr)
				continue;

			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
				continue;

			/*
			 * KAME specific: detached prefixes should not be
			 * on-link.
			 */
			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
				continue;

			if (opr->ndpr_plen == pr->ndpr_plen &&
			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
				int e;

				if ((e = nd6_prefix_onlink(opr)) != 0) {
					nd6log((LOG_ERR,
					    "nd6_prefix_offlink: failed to "
					    "recover a prefix %s/%d from %s "
					    "to %s (errno = %d)\n",
					    inet_ntop(AF_INET6,
						&pr->ndpr_prefix.sin6_addr,
						addr, sizeof(addr)),
					    opr->ndpr_plen, ifp->if_xname,
					    opr->ndpr_ifp->if_xname, e));
				}
			}
		}
	}

	return (error);
}

struct in6_ifaddr *
in6_ifadd(struct nd_prefix *pr, int privacy)
{
	struct ifnet *ifp = pr->ndpr_ifp;
	struct ifaddr *ifa;
	struct in6_aliasreq ifra;
	struct in6_ifaddr *ia6;
	int error, s, plen0;
	struct in6_addr mask, rand_ifid;
	int prefixlen = pr->ndpr_plen;

	in6_prefixlen2mask(&mask, prefixlen);

	/*
	 * find a link-local address (will be interface ID).
	 * Is it really mandatory? Theoretically, a global or a site-local
	 * address can be configured without a link-local address, if we
	 * have a unique interface identifier...
	 *
	 * it is not mandatory to have a link-local address, we can generate
	 * interface identifier on the fly.  we do this because:
	 * (1) it should be the easiest way to find interface identifier.
	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
	 * for multiple addresses on a single interface, and possible shortcut
	 * of DAD.  we omitted DAD for this reason in the past.
	 * (3) a user can prevent autoconfiguration of global address
	 * by removing link-local address by hand (this is partly because we
	 * don't have other way to control the use of IPv6 on a interface.
	 * this has been our design choice - cf. NRL's "ifconfig auto").
	 * (4) it is easier to manage when an interface has addresses
	 * with the same interface identifier, than to have multiple addresses
	 * with different interface identifiers.
	 */
	ifa = &in6ifa_ifpforlinklocal(ifp, 0)->ia_ifa; /* 0 is OK? */
	if (ifa)
		ia6 = ifatoia6(ifa);
	else
		return NULL;

	/* prefixlen + ifidlen must be equal to 128 */
	plen0 = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
	if (prefixlen != plen0) {
		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
		    "(prefix=%d ifid=%d)\n",
		    ifp->if_xname, prefixlen, 128 - plen0));
		return NULL;
	}

	/* make ifaddr */
	bzero(&ifra, sizeof(ifra));
	strncpy(ifra.ifra_name, ifp->if_xname, sizeof(ifra.ifra_name));
	ifra.ifra_addr.sin6_family = AF_INET6;
	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
	/* prefix */
	bcopy(&pr->ndpr_prefix.sin6_addr, &ifra.ifra_addr.sin6_addr,
	    sizeof(ifra.ifra_addr.sin6_addr));
	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];

	/* interface ID */
	if (privacy) {
		ifra.ifra_flags |= IN6_IFF_PRIVACY;
		bcopy(&pr->ndpr_prefix.sin6_addr, &rand_ifid,
		    sizeof(rand_ifid));
		in6_get_rand_ifid(ifp, &rand_ifid);
		ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
		    (rand_ifid.s6_addr32[0] & ~mask.s6_addr32[0]);
		ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
		    (rand_ifid.s6_addr32[1] & ~mask.s6_addr32[1]);
		ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
		    (rand_ifid.s6_addr32[2] & ~mask.s6_addr32[2]);
		ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
		    (rand_ifid.s6_addr32[3] & ~mask.s6_addr32[3]);
	} else {
		ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
		ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
		ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
		ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
	}

	/* new prefix mask. */
	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
	ifra.ifra_prefixmask.sin6_family = AF_INET6;
	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
	    sizeof(ifra.ifra_prefixmask.sin6_addr));

	/*
	 * lifetime.
	 * XXX: in6_init_address_ltimes would override these values later.
	 * We should reconsider this logic.
	 */
	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;

	if (privacy) {
	    if (ifra.ifra_lifetime.ia6t_vltime > ND6_PRIV_VALID_LIFETIME)
		ifra.ifra_lifetime.ia6t_vltime = ND6_PRIV_VALID_LIFETIME;
	    if (ifra.ifra_lifetime.ia6t_pltime > ND6_PRIV_PREFERRED_LIFETIME)
		ifra.ifra_lifetime.ia6t_pltime = ND6_PRIV_PREFERRED_LIFETIME
			- arc4random_uniform(ND6_PRIV_MAX_DESYNC_FACTOR);
	}

	/* XXX: scope zone ID? */

	ifra.ifra_flags |= IN6_IFF_AUTOCONF|IN6_IFF_TENTATIVE;

	/* allocate ifaddr structure, link into chain, etc. */
	s = splsoftnet();
	error = in6_update_ifa(ifp, &ifra, NULL);
	splx(s);

	if (error != 0) {
		char addr[INET6_ADDRSTRLEN];

		nd6log((LOG_ERR,
		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
		    inet_ntop(AF_INET6,	&ifra.ifra_addr.sin6_addr,
			addr, sizeof(addr)),
		    ifp->if_xname, error));
		return (NULL);	/* ifaddr must not have been allocated. */
	}

	ia6 = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);

	/* Perform DAD, if needed. */
	if (ia6 != NULL && ia6->ia6_flags & IN6_IFF_TENTATIVE)
		nd6_dad_start(&ia6->ia_ifa);

	return (ia6);
}

int
in6_init_prefix_ltimes(struct nd_prefix *ndpr)
{

	/* check if preferred lifetime > valid lifetime.  RFC2462 5.5.3 (c) */
	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
		nd6log((LOG_INFO, "in6_init_prefix_ltimes: preferred lifetime"
		    "(%d) is greater than valid lifetime(%d)\n",
		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime));
		return (EINVAL);
	}
	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
		ndpr->ndpr_preferred = 0;
	else
		ndpr->ndpr_preferred = time_second + ndpr->ndpr_pltime;
	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
		ndpr->ndpr_expire = 0;
	else
		ndpr->ndpr_expire = time_second + ndpr->ndpr_vltime;

	return 0;
}

void
in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
{

	/* Valid lifetime must not be updated unless explicitly specified. */
	/* init ia6t_expire */
	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
		lt6->ia6t_expire = 0;
	else {
		lt6->ia6t_expire = time_second;
		lt6->ia6t_expire += lt6->ia6t_vltime;
	}

	/* init ia6t_preferred */
	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
		lt6->ia6t_preferred = 0;
	else {
		lt6->ia6t_preferred = time_second;
		lt6->ia6t_preferred += lt6->ia6t_pltime;
	}
}

/*
 * Delete all the routing table entries that use the specified gateway.
 * XXX: this function causes search through all entries of routing table, so
 * it shouldn't be called when acting as a router.
 */
void
rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
{
	int s;

	/* We'll care only link-local addresses */
	if (!IN6_IS_ADDR_LINKLOCAL(gateway))
		return;

	/* XXX: hack for KAME's link-local address kludge */
	gateway->s6_addr16[1] = htons(ifp->if_index);

	s = splsoftnet();
	rtable_walk(ifp->if_rdomain, AF_INET6, rt6_deleteroute, gateway);
	splx(s);
}

int
rt6_deleteroute(struct rtentry *rt, void *arg, unsigned int id)
{
	struct rt_addrinfo info;
	struct in6_addr *gate = (struct in6_addr *)arg;
	struct sockaddr_in6 sa_mask;
	int error;

	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
		return (0);

	if (!IN6_ARE_ADDR_EQUAL(gate, &satosin6(rt->rt_gateway)->sin6_addr))
		return (0);

	/*
	 * Do not delete a static route.
	 * XXX: this seems to be a bit ad-hoc. Should we consider the
	 * 'cloned' bit instead?
	 */
	if ((rt->rt_flags & RTF_STATIC) != 0)
		return (0);

	/*
	 * We delete only host route. This means, in particular, we don't
	 * delete default route.
	 */
	if ((rt->rt_flags & RTF_HOST) == 0)
		return (0);

	bzero(&info, sizeof(info));
	info.rti_flags =  rt->rt_flags;
	info.rti_info[RTAX_DST] = rt_key(rt);
	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
	info.rti_info[RTAX_NETMASK] = rt_plen2mask(rt, &sa_mask);
	error = rtrequest(RTM_DELETE, &info, RTP_ANY, NULL, id);
	if (error != 0)
		return (error);

	return (EAGAIN);
}