summaryrefslogtreecommitdiffstats
path: root/src/osd/PGLog.h
blob: 69ca1d20c740228cea8eafadc1429e3260dd2f47 (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
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- 
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 * Copyright (C) 2013 Cloudwatt <libre.licensing@cloudwatt.com>
 *
 * Author: Loic Dachary <loic@dachary.org>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software 
 * Foundation.  See file COPYING.
 * 
 */
#pragma once

// re-include our assert to clobber boost's
#include "include/ceph_assert.h"
#include "include/common_fwd.h"
#include "osd_types.h"
#include "os/ObjectStore.h"
#include <list>

#ifdef WITH_SEASTAR
#include <seastar/core/future.hh>
#include "crimson/os/futurized_store.h"
#include "crimson/os/cyanstore/cyan_collection.h"
#endif

/** @name PG Log
 *
 * The pg log serves three primary purposes:
 *
 * 1) improving recovery speed
 *
 * 2) detecting duplicate ops
 *
 * 3) making erasure coded updates safe
 *
 * For (1), the main data type is pg_log_entry_t.  this is indexed in
 * memory by the IndexedLog class - this is where most of the logic
 * surrounding pg log is kept, even though the low level types are in
 * src/osd/osd_types.h
 *
 * (2) uses a type which is a subset of the full log entry, containing
 * just the pieces we need to identify and respond to a duplicate
 * request.
 *
 * As we trim the log, we convert pg_log_entry_t to smaller
 * pg_log_dup_t, and finally remove them once we reach a higher
 * limit. This is controlled by a few options:
 *
 * osd_min_pg_log_entries osd_max_pg_log_entries
 * osd_pg_log_dups_tracked
 *
 * For example, with a min of 100, max of 1000, and dups tracked of
 * 3000, the log entries and dups stored would span the following
 * versions, assuming the current earliest is version 1:
 *
 *   version: 3000 2001 2000 1 [ pg log entries ] [ pg log dups ]
 *
 * after osd_pg_log_trim_min subsequent writes to this PG, the log
 * would be trimmed to look like:
 *
 *   version: 3100 2101 2100 101 [ pg log entries ] [ pg log dups ]
 *
 * (3) means tracking the previous state of an object, so that we can
 * rollback to that prior state if necessary. It's only used for
 * erasure coding. Consider an erasure code of 4+2, for example.
 *
 * This means we split the object into 4 pieces (called shards) and
 * compute 2 parity shards. Each of these shards is stored on a
 * separate OSD. As long as 4 shards are the same version, we can
 * recover the remaining 2 by computation. Imagine during a write, 3
 * of the osds go down and restart, resulting in shards 0,1,2
 * reflecting version A and shards 3,4,5 reflecting version B, after
 * the write.
 *
 * If we had no way to reconstruct version A for another shard, we
 * would have lost the object.
 *
 * The actual data for rollback is stored in a look-aside object and
 * is removed once the EC write commits on all shards. The pg log just
 * stores the versions so we can tell how far we can rollback, and a
 * description of the type of operation for each log entry.  Beyond
 * the pg log, see PGBackend::Trimmer and PGBackend::RollbackVisitor
 * for more details on this.
 *
 * An important implication of this is that although the pg log length
 * is normally bounded, under extreme conditions, with many EC I/Os
 * outstanding, the log may grow beyond that point because we need to
 * keep the rollback information for all outstanding EC I/O.
 *
 * For more on pg log bounds, see where it is calculated in
 * PeeringState::calc_trim_to_aggressive().
 *
 * For more details on how peering uses the pg log, and architectural
 * reasons for its existence, see:
 *
 *   doc/dev/osd_internals/log_based_pg.rst
 *
 */

constexpr auto PGLOG_INDEXED_OBJECTS          = 1 << 0;
constexpr auto PGLOG_INDEXED_CALLER_OPS       = 1 << 1;
constexpr auto PGLOG_INDEXED_EXTRA_CALLER_OPS = 1 << 2;
constexpr auto PGLOG_INDEXED_DUPS             = 1 << 3;
constexpr auto PGLOG_INDEXED_ALL              = PGLOG_INDEXED_OBJECTS 
                                              | PGLOG_INDEXED_CALLER_OPS 
                                              | PGLOG_INDEXED_EXTRA_CALLER_OPS 
                                              | PGLOG_INDEXED_DUPS;

struct PGLog : DoutPrefixProvider {
  std::ostream& gen_prefix(std::ostream& out) const override {
    return out;
  }
  unsigned get_subsys() const override {
    return static_cast<unsigned>(ceph_subsys_osd);
  }
  CephContext *get_cct() const override {
    return cct;
  }

  ////////////////////////////// sub classes //////////////////////////////
  struct LogEntryHandler {
    virtual void rollback(
      const pg_log_entry_t &entry) = 0;
    virtual void rollforward(
      const pg_log_entry_t &entry) = 0;
    virtual void trim(
      const pg_log_entry_t &entry) = 0;
    virtual void remove(
      const hobject_t &hoid) = 0;
    virtual void try_stash(
      const hobject_t &hoid,
      version_t v) = 0;
    virtual ~LogEntryHandler() {}
  };
  using LogEntryHandlerRef = std::unique_ptr<LogEntryHandler>;

public:
  /**
   * IndexLog - adds in-memory index of the log, by oid.
   * plus some methods to manipulate it all.
   */
  struct IndexedLog : public pg_log_t {
    mutable ceph::unordered_map<hobject_t,pg_log_entry_t*> objects;  // ptrs into log.  be careful!
    mutable ceph::unordered_map<osd_reqid_t,pg_log_entry_t*> caller_ops;
    mutable ceph::unordered_multimap<osd_reqid_t,pg_log_entry_t*> extra_caller_ops;
    mutable ceph::unordered_map<osd_reqid_t,pg_log_dup_t*> dup_index;

    // recovery pointers
    std::list<pg_log_entry_t>::iterator complete_to; // not inclusive of referenced item
    version_t last_requested = 0;               // last object requested by primary

    //
  private:
    mutable __u16 indexed_data = 0;
    /**
     * rollback_info_trimmed_to_riter points to the first log entry <=
     * rollback_info_trimmed_to
     *
     * It's a reverse_iterator because rend() is a natural representation for
     * tail, and rbegin() works nicely for head.
     */
    mempool::osd_pglog::list<pg_log_entry_t>::reverse_iterator
      rollback_info_trimmed_to_riter;

    /*
     * return true if we need to mark the pglog as dirty
     */
    template <typename F>
    bool advance_can_rollback_to(eversion_t to, F &&f) {
      bool dirty_log = to > can_rollback_to || to > rollback_info_trimmed_to;
      if (dirty_log) {
	if (to > can_rollback_to)
	  can_rollback_to = to;

	if (to > rollback_info_trimmed_to)
	  rollback_info_trimmed_to = to;
      }

      while (rollback_info_trimmed_to_riter != log.rbegin()) {
	--rollback_info_trimmed_to_riter;
	if (rollback_info_trimmed_to_riter->version > rollback_info_trimmed_to) {
	  ++rollback_info_trimmed_to_riter;
	  break;
	}
	f(*rollback_info_trimmed_to_riter);
      }

      return dirty_log;
    }

    void reset_rollback_info_trimmed_to_riter() {
      rollback_info_trimmed_to_riter = log.rbegin();
      while (rollback_info_trimmed_to_riter != log.rend() &&
	     rollback_info_trimmed_to_riter->version > rollback_info_trimmed_to)
	++rollback_info_trimmed_to_riter;
    }

    // indexes objects, caller ops and extra caller ops
  public:
    IndexedLog() :
      complete_to(log.end()),
      last_requested(0),
      indexed_data(0),
      rollback_info_trimmed_to_riter(log.rbegin())
    { }

    template <typename... Args>
    explicit IndexedLog(Args&&... args) :
      pg_log_t(std::forward<Args>(args)...),
      complete_to(log.end()),
      last_requested(0),
      indexed_data(0),
      rollback_info_trimmed_to_riter(log.rbegin())
    {
      reset_rollback_info_trimmed_to_riter();
      index();
    }

    IndexedLog(const IndexedLog &rhs) :
      pg_log_t(rhs),
      complete_to(log.end()),
      last_requested(rhs.last_requested),
      indexed_data(0),
      rollback_info_trimmed_to_riter(log.rbegin())
    {
      reset_rollback_info_trimmed_to_riter();
      index(rhs.indexed_data);
    }

    IndexedLog &operator=(const IndexedLog &rhs) {
      this->~IndexedLog();
      new (this) IndexedLog(rhs);
      return *this;
    }

    void trim_rollback_info_to(eversion_t to, LogEntryHandler *h) {
      advance_can_rollback_to(
	to,
	[&](pg_log_entry_t &entry) {
	  h->trim(entry);
	});
    }
    bool roll_forward_to(eversion_t to, LogEntryHandler *h) {
      return advance_can_rollback_to(
	to,
	[&](pg_log_entry_t &entry) {
	  h->rollforward(entry);
	});
    }

    void skip_can_rollback_to_to_head() {
      advance_can_rollback_to(head, [&](const pg_log_entry_t &entry) {});
    }

    mempool::osd_pglog::list<pg_log_entry_t> rewind_from_head(eversion_t newhead) {
      auto divergent = pg_log_t::rewind_from_head(newhead);
      index();
      reset_rollback_info_trimmed_to_riter();
      return divergent;
    }

    template <typename T>
    void scan_log_after(
      const eversion_t &bound, ///< [in] scan entries > bound
      T &&f) const {
      auto iter = log.rbegin();
      while (iter != log.rend() && iter->version > bound)
	++iter;

      while (true) {
	if (iter == log.rbegin())
	  break;
	f(*(--iter));
      }
    }

    /****/
    void claim_log_and_clear_rollback_info(const pg_log_t& o) {
      // we must have already trimmed the old entries
      ceph_assert(rollback_info_trimmed_to == head);
      ceph_assert(rollback_info_trimmed_to_riter == log.rbegin());

      *this = IndexedLog(o);

      skip_can_rollback_to_to_head();
      index();
    }

    void split_out_child(
      pg_t child_pgid,
      unsigned split_bits,
      IndexedLog *target);

    void zero() {
      // we must have already trimmed the old entries
      ceph_assert(rollback_info_trimmed_to == head);
      ceph_assert(rollback_info_trimmed_to_riter == log.rbegin());

      unindex();
      pg_log_t::clear();
      rollback_info_trimmed_to_riter = log.rbegin();
      reset_recovery_pointers();
    }
    void clear() {
      skip_can_rollback_to_to_head();
      zero();
    }
    void reset_recovery_pointers() {
      complete_to = log.end();
      last_requested = 0;
    }

    bool logged_object(const hobject_t& oid) const {
      if (!(indexed_data & PGLOG_INDEXED_OBJECTS)) {
         index_objects();
      }
      return objects.count(oid);
    }

    bool logged_req(const osd_reqid_t &r) const {
      if (!(indexed_data & PGLOG_INDEXED_CALLER_OPS)) {
        index_caller_ops();
      }
      if (!caller_ops.count(r)) {
        if (!(indexed_data & PGLOG_INDEXED_EXTRA_CALLER_OPS)) {
          index_extra_caller_ops();
        }
        return extra_caller_ops.count(r);
      }
      return true;
    }

    bool get_request(
      const osd_reqid_t &r,
      eversion_t *version,
      version_t *user_version,
      int *return_code,
      std::vector<pg_log_op_return_item_t> *op_returns) const
    {
      ceph_assert(version);
      ceph_assert(user_version);
      ceph_assert(return_code);
      if (!(indexed_data & PGLOG_INDEXED_CALLER_OPS)) {
        index_caller_ops();
      }
      auto p = caller_ops.find(r);
      if (p != caller_ops.end()) {
	*version = p->second->version;
	*user_version = p->second->user_version;
	*return_code = p->second->return_code;
	*op_returns = p->second->op_returns;
	return true;
      }

      // warning: we will return *a* request for this reqid, but not
      // necessarily the most recent.
      if (!(indexed_data & PGLOG_INDEXED_EXTRA_CALLER_OPS)) {
        index_extra_caller_ops();
      }
      p = extra_caller_ops.find(r);
      if (p != extra_caller_ops.end()) {
	uint32_t idx = 0;
	for (auto i = p->second->extra_reqids.begin();
	     i != p->second->extra_reqids.end();
	     ++idx, ++i) {
	  if (i->first == r) {
	    *version = p->second->version;
	    *user_version = i->second;
	    *return_code = p->second->return_code;
	    *op_returns = p->second->op_returns;
	    if (*return_code >= 0) {
	      auto it = p->second->extra_reqid_return_codes.find(idx);
	      if (it != p->second->extra_reqid_return_codes.end()) {
		*return_code = it->second;
	      }
	    }
	    return true;
	  }
	}
	ceph_abort_msg("in extra_caller_ops but not extra_reqids");
      }

      if (!(indexed_data & PGLOG_INDEXED_DUPS)) {
        index_dups();
      }
      auto q = dup_index.find(r);
      if (q != dup_index.end()) {
	*version = q->second->version;
	*user_version = q->second->user_version;
	*return_code = q->second->return_code;
	*op_returns = q->second->op_returns;
	return true;
      }

      return false;
    }

    bool has_write_since(const hobject_t &oid, const eversion_t &bound) const {
      for (auto i = log.rbegin(); i != log.rend(); ++i) {
	if (i->version <= bound)
	  return false;
	if (i->soid.get_head() == oid.get_head())
	  return true;
      }
      return false;
    }

    /// get a (bounded) std::list of recent reqids for the given object
    void get_object_reqids(const hobject_t& oid, unsigned max,
			   mempool::osd_pglog::vector<std::pair<osd_reqid_t, version_t> > *pls,
			   mempool::osd_pglog::map<uint32_t, int> *return_codes) const {
       // make sure object is present at least once before we do an
       // O(n) search.
      if (!(indexed_data & PGLOG_INDEXED_OBJECTS)) {
        index_objects();
      }
      if (objects.count(oid) == 0)
	return;

      for (auto i = log.rbegin(); i != log.rend(); ++i) {
	if (i->soid == oid) {
	  if (i->reqid_is_indexed()) {
	    if (i->op == pg_log_entry_t::ERROR) {
	      // propagate op errors to the cache tier's PG log
	      return_codes->emplace(pls->size(), i->return_code);
	    }
	    pls->push_back(std::make_pair(i->reqid, i->user_version));
	  }

	  pls->insert(pls->end(), i->extra_reqids.begin(), i->extra_reqids.end());
	  if (pls->size() >= max) {
	    if (pls->size() > max) {
	      pls->resize(max);
	    }
	    return;
	  }
	}
      }
    }

    void index(__u16 to_index = PGLOG_INDEXED_ALL) const {
      // if to_index is 0, no need to run any of this code, especially
      // loop below; this can happen with copy constructor for
      // IndexedLog (and indirectly through assignment operator)
      if (!to_index) return;

      if (to_index & PGLOG_INDEXED_OBJECTS)
	objects.clear();
      if (to_index & PGLOG_INDEXED_CALLER_OPS)
	caller_ops.clear();
      if (to_index & PGLOG_INDEXED_EXTRA_CALLER_OPS)
	extra_caller_ops.clear();
      if (to_index & PGLOG_INDEXED_DUPS) {
	dup_index.clear();
	for (auto& i : dups) {
	  dup_index[i.reqid] = const_cast<pg_log_dup_t*>(&i);
	}
      }

      constexpr __u16 any_log_entry_index =
	PGLOG_INDEXED_OBJECTS |
	PGLOG_INDEXED_CALLER_OPS |
	PGLOG_INDEXED_EXTRA_CALLER_OPS;

      if (to_index & any_log_entry_index) {
	for (auto i = log.begin(); i != log.end(); ++i) {
	  if (to_index & PGLOG_INDEXED_OBJECTS) {
	    if (i->object_is_indexed()) {
	      objects[i->soid] = const_cast<pg_log_entry_t*>(&(*i));
	    }
	  }

	  if (to_index & PGLOG_INDEXED_CALLER_OPS) {
	    if (i->reqid_is_indexed()) {
	      caller_ops[i->reqid] = const_cast<pg_log_entry_t*>(&(*i));
	    }
	  }

	  if (to_index & PGLOG_INDEXED_EXTRA_CALLER_OPS) {
	    for (auto j = i->extra_reqids.begin();
		 j != i->extra_reqids.end();
		 ++j) {
	      extra_caller_ops.insert(
		std::make_pair(j->first, const_cast<pg_log_entry_t*>(&(*i))));
	    }
	  }
	}
      }

      indexed_data |= to_index;
    }

    void index_objects() const {
      index(PGLOG_INDEXED_OBJECTS);
    }

    void index_caller_ops() const {
      index(PGLOG_INDEXED_CALLER_OPS);
    }

    void index_extra_caller_ops() const {
      index(PGLOG_INDEXED_EXTRA_CALLER_OPS);
    }

    void index_dups() const {
      index(PGLOG_INDEXED_DUPS);
    }

    void index(pg_log_entry_t& e) {
      if ((indexed_data & PGLOG_INDEXED_OBJECTS) && e.object_is_indexed()) {
        if (objects.count(e.soid) == 0 ||
            objects[e.soid]->version < e.version)
          objects[e.soid] = &e;
      }
      if (indexed_data & PGLOG_INDEXED_CALLER_OPS) {
	// divergent merge_log indexes new before unindexing old
        if (e.reqid_is_indexed()) {
	  caller_ops[e.reqid] = &e;
        }
      }
      if (indexed_data & PGLOG_INDEXED_EXTRA_CALLER_OPS) {
        for (auto j = e.extra_reqids.begin();
	     j != e.extra_reqids.end();
	     ++j) {
	  extra_caller_ops.insert(std::make_pair(j->first, &e));
        }
      }
    }

    void unindex() {
      objects.clear();
      caller_ops.clear();
      extra_caller_ops.clear();
      dup_index.clear();
      indexed_data = 0;
    }

    void unindex(const pg_log_entry_t& e) {
      // NOTE: this only works if we remove from the _tail_ of the log!
      if (indexed_data & PGLOG_INDEXED_OBJECTS) {
	auto it = objects.find(e.soid);
        if (it != objects.end() && it->second->version == e.version)
          objects.erase(it);
      }
      if (e.reqid_is_indexed()) {
        if (indexed_data & PGLOG_INDEXED_CALLER_OPS) {
	  auto it = caller_ops.find(e.reqid);
	  // divergent merge_log indexes new before unindexing old
          if (it != caller_ops.end() && it->second == &e)
            caller_ops.erase(it);
        }
      }
      if (indexed_data & PGLOG_INDEXED_EXTRA_CALLER_OPS) {
        for (auto j = e.extra_reqids.begin();
             j != e.extra_reqids.end();
             ++j) {
          for (auto k = extra_caller_ops.find(j->first);
               k != extra_caller_ops.end() && k->first == j->first;
               ++k) {
            if (k->second == &e) {
              extra_caller_ops.erase(k);
              break;
            }
          }
        }
      }
    }

    void index(pg_log_dup_t& e) {
      if (indexed_data & PGLOG_INDEXED_DUPS) {
	dup_index[e.reqid] = &e;
      }
    }

    void unindex(const pg_log_dup_t& e) {
      if (indexed_data & PGLOG_INDEXED_DUPS) {
	auto i = dup_index.find(e.reqid);
	if (i != dup_index.end()) {
	  dup_index.erase(i);
	}
      }
    }

    // actors
    void add(const pg_log_entry_t& e, bool applied = true) {
      if (!applied) {
	ceph_assert(get_can_rollback_to() == head);
      }

      // make sure our buffers don't pin bigger buffers
      e.mod_desc.trim_bl();

      // add to log
      log.push_back(e);

      // riter previously pointed to the previous entry
      if (rollback_info_trimmed_to_riter == log.rbegin())
	++rollback_info_trimmed_to_riter;

      ceph_assert(e.version > head);
      ceph_assert(head.version == 0 || e.version.version > head.version);
      head = e.version;

      // to our index
      if ((indexed_data & PGLOG_INDEXED_OBJECTS) && e.object_is_indexed()) {
        objects[e.soid] = &(log.back());
      }
      if (indexed_data & PGLOG_INDEXED_CALLER_OPS) {
        if (e.reqid_is_indexed()) {
	  caller_ops[e.reqid] = &(log.back());
        }
      }

      if (indexed_data & PGLOG_INDEXED_EXTRA_CALLER_OPS) {
        for (auto j = e.extra_reqids.begin();
	     j != e.extra_reqids.end();
	     ++j) {
	  extra_caller_ops.insert(std::make_pair(j->first, &(log.back())));
        }
      }

      if (!applied) {
	skip_can_rollback_to_to_head();
      }
    } // add

    void trim(
      CephContext* cct,
      eversion_t s,
      std::set<eversion_t> *trimmed,
      std::set<std::string>* trimmed_dups,
      eversion_t *write_from_dups);

    std::ostream& print(std::ostream& out) const;
  }; // IndexedLog


protected:
  //////////////////// data members ////////////////////

  pg_missing_tracker_t missing;
  IndexedLog  log;

  eversion_t dirty_to;         ///< must clear/writeout all keys <= dirty_to
  eversion_t dirty_from;       ///< must clear/writeout all keys >= dirty_from
  eversion_t writeout_from;    ///< must writout keys >= writeout_from
  std::set<eversion_t> trimmed;     ///< must clear keys in trimmed
  eversion_t dirty_to_dups;    ///< must clear/writeout all dups <= dirty_to_dups
  eversion_t dirty_from_dups;  ///< must clear/writeout all dups >= dirty_from_dups
  eversion_t write_from_dups;  ///< must write keys >= write_from_dups
  std::set<std::string> trimmed_dups;    ///< must clear keys in trimmed_dups
  CephContext *cct;
  bool pg_log_debug;
  /// Log is clean on [dirty_to, dirty_from)
  bool touched_log;
  bool dirty_log;
  bool clear_divergent_priors;
  bool may_include_deletes_in_missing_dirty = false;

  void mark_dirty_to(eversion_t to) {
    if (to > dirty_to)
      dirty_to = to;
  }
  void mark_dirty_from(eversion_t from) {
    if (from < dirty_from)
      dirty_from = from;
  }
  void mark_writeout_from(eversion_t from) {
    if (from < writeout_from)
      writeout_from = from;
  }
  void mark_dirty_to_dups(eversion_t to) {
    if (to > dirty_to_dups)
      dirty_to_dups = to;
  }
  void mark_dirty_from_dups(eversion_t from) {
    if (from < dirty_from_dups)
      dirty_from_dups = from;
  }
public:
  bool needs_write() const {
    return !touched_log || is_dirty();
  }

  bool is_dirty() const {
    return dirty_log ||
      (dirty_to != eversion_t()) ||
      (dirty_from != eversion_t::max()) ||
      (writeout_from != eversion_t::max()) ||
      !(trimmed.empty()) ||
      !missing.is_clean() ||
      !(trimmed_dups.empty()) ||
      (dirty_to_dups != eversion_t()) ||
      (dirty_from_dups != eversion_t::max()) ||
      (write_from_dups != eversion_t::max()) ||
      may_include_deletes_in_missing_dirty;
  }

  void mark_log_for_rewrite() {
    mark_dirty_to(eversion_t::max());
    mark_dirty_from(eversion_t());
    mark_dirty_to_dups(eversion_t::max());
    mark_dirty_from_dups(eversion_t());
    touched_log = false;
  }
  bool get_may_include_deletes_in_missing_dirty() const {
    return may_include_deletes_in_missing_dirty;
  }
protected:

  /// DEBUG
  std::set<std::string> log_keys_debug;
  static void clear_after(std::set<std::string> *log_keys_debug, const std::string &lb) {
    if (!log_keys_debug)
      return;
    for (auto i = log_keys_debug->lower_bound(lb);
	 i != log_keys_debug->end();
	 log_keys_debug->erase(i++));
  }
  static void clear_up_to(std::set<std::string> *log_keys_debug, const std::string &ub) {
    if (!log_keys_debug)
      return;
    for (auto i = log_keys_debug->begin();
	 i != log_keys_debug->end() && *i < ub;
	 log_keys_debug->erase(i++));
  }

  void check();
  void undirty() {
    dirty_to = eversion_t();
    dirty_from = eversion_t::max();
    touched_log = true;
    dirty_log = false;
    trimmed.clear();
    trimmed_dups.clear();
    writeout_from = eversion_t::max();
    check();
    missing.flush();
    dirty_to_dups = eversion_t();
    dirty_from_dups = eversion_t::max();
    write_from_dups = eversion_t::max();
  }
public:

  // cppcheck-suppress noExplicitConstructor
  PGLog(CephContext *cct) :
    dirty_from(eversion_t::max()),
    writeout_from(eversion_t::max()),
    dirty_from_dups(eversion_t::max()),
    write_from_dups(eversion_t::max()),
    cct(cct),
    pg_log_debug(!(cct && !(cct->_conf->osd_debug_pg_log_writeout))),
    touched_log(false),
    dirty_log(false),
    clear_divergent_priors(false)
  { }

  void reset_backfill();

  void clear();

  //////////////////// get or std::set missing ////////////////////

  const pg_missing_tracker_t& get_missing() const { return missing; }

  void missing_add(const hobject_t& oid, eversion_t need, eversion_t have, bool is_delete=false) {
    missing.add(oid, need, have, is_delete);
  }

  void missing_add_next_entry(const pg_log_entry_t& e) {
    missing.add_next_event(e);
  }

  //////////////////// get or std::set log ////////////////////

  const IndexedLog &get_log() const { return log; }

  const eversion_t &get_tail() const { return log.tail; }

  void set_tail(eversion_t tail) { log.tail = tail; }

  const eversion_t &get_head() const { return log.head; }

  void set_head(eversion_t head) { log.head = head; }

  void set_last_requested(version_t last_requested) {
    log.last_requested = last_requested;
  }

  void index() { log.index(); }

  void unindex() { log.unindex(); }

  void add(const pg_log_entry_t& e, bool applied = true) {
    mark_writeout_from(e.version);
    log.add(e, applied);
  }

  void reset_recovery_pointers() { log.reset_recovery_pointers(); }

  static void clear_info_log(
    spg_t pgid,
    ObjectStore::Transaction *t);

  void trim(
    eversion_t trim_to,
    pg_info_t &info,
    bool transaction_applied = true,
    bool async = false);

  void roll_forward_to(
    eversion_t roll_forward_to,
    LogEntryHandler *h) {
    if (log.roll_forward_to(
	  roll_forward_to,
	  h))
      dirty_log = true;
  }

  eversion_t get_can_rollback_to() const {
    return log.get_can_rollback_to();
  }

  void roll_forward(LogEntryHandler *h) {
    roll_forward_to(
      log.head,
      h);
  }

  void skip_rollforward() {
    log.skip_can_rollback_to_to_head();
  }

  //////////////////// get or std::set log & missing ////////////////////

  void reset_backfill_claim_log(const pg_log_t &o, LogEntryHandler *h) {
    log.trim_rollback_info_to(log.head, h);
    log.claim_log_and_clear_rollback_info(o);
    missing.clear();
    mark_dirty_to(eversion_t::max());
    mark_dirty_to_dups(eversion_t::max());
  }

  void split_into(
      pg_t child_pgid,
      unsigned split_bits,
      PGLog *opg_log) {
    log.split_out_child(child_pgid, split_bits, &opg_log->log);
    missing.split_into(child_pgid, split_bits, &(opg_log->missing));
    opg_log->mark_dirty_to(eversion_t::max());
    opg_log->mark_dirty_to_dups(eversion_t::max());
    mark_dirty_to(eversion_t::max());
    mark_dirty_to_dups(eversion_t::max());
    if (missing.may_include_deletes) {
      opg_log->set_missing_may_contain_deletes();
    }
  }

  void merge_from(
    const std::vector<PGLog*>& sources,
    eversion_t last_update) {
    unindex();
    missing.clear();

    std::vector<pg_log_t*> slogs;
    for (auto s : sources) {
      slogs.push_back(&s->log);
    }
    log.merge_from(slogs, last_update);

    index();

    mark_log_for_rewrite();
  }

  void recover_got(hobject_t oid, eversion_t v, pg_info_t &info) {
    if (missing.is_missing(oid, v)) {
      missing.got(oid, v);
      info.stats.stats.sum.num_objects_missing = missing.num_missing();

      // raise last_complete?
      if (missing.get_items().empty()) {
	log.complete_to = log.log.end();
	info.last_complete = info.last_update;
      }
      auto oldest_need = missing.get_oldest_need();
      while (log.complete_to != log.log.end()) {
	if (oldest_need <= log.complete_to->version)
	  break;
	if (info.last_complete < log.complete_to->version)
	  info.last_complete = log.complete_to->version;
	++log.complete_to;
      }
    }

    ceph_assert(log.get_can_rollback_to() >= v);
  }

  void reset_complete_to(pg_info_t *info) {
    if (log.log.empty()) // caller is split_into()
      return;
    log.complete_to = log.log.begin();
    ceph_assert(log.complete_to != log.log.end());
    auto oldest_need = missing.get_oldest_need();
    if (oldest_need != eversion_t()) {
      while (log.complete_to->version < oldest_need) {
        ++log.complete_to;
        ceph_assert(log.complete_to != log.log.end());
      }
    }
    if (!info)
      return;
    if (log.complete_to == log.log.begin()) {
      info->last_complete = eversion_t();
    } else {
      --log.complete_to;
      info->last_complete = log.complete_to->version;
      ++log.complete_to;
    }
  }

  void activate_not_complete(pg_info_t &info) {
    reset_complete_to(&info);
    log.last_requested = 0;
  }

  void proc_replica_log(pg_info_t &oinfo,
			const pg_log_t &olog,
			pg_missing_t& omissing, pg_shard_t from) const;

  void set_missing_may_contain_deletes() {
    missing.may_include_deletes = true;
    may_include_deletes_in_missing_dirty = true;
  }

  void rebuild_missing_set_with_deletes(ObjectStore *store,
					ObjectStore::CollectionHandle& ch,
					const pg_info_t &info);

protected:
  static void split_by_object(
    mempool::osd_pglog::list<pg_log_entry_t> &entries,
    std::map<hobject_t, mempool::osd_pglog::list<pg_log_entry_t>> *out_entries) {
    while (!entries.empty()) {
      auto &out_list = (*out_entries)[entries.front().soid];
      out_list.splice(out_list.end(), entries, entries.begin());
    }
  }

  /**
   * _merge_object_divergent_entries
   *
   * There are 5 distinct cases:
   * 1) There is a more recent update: in this case we assume we adjusted the
   *    store and missing during merge_log
   * 2) The first entry in the divergent sequence is a create.  This might
   *    either be because the object is a clone or because prior_version is
   *    eversion_t().  In this case the object does not exist and we must
   *    adjust missing and the store to match.
   * 3) We are currently missing the object.  In this case, we adjust the
   *    missing to our prior_version taking care to add a divergent_prior
   *    if necessary
   * 4) We can rollback all of the entries.  In this case, we do so using
   *    the rollbacker and return -- the object does not go into missing.
   * 5) We cannot rollback at least 1 of the entries.  In this case, we
   *    clear the object out of the store and add a missing entry at
   *    prior_version taking care to add a divergent_prior if
   *    necessary.
   */
  template <typename missing_type>
  static void _merge_object_divergent_entries(
    const IndexedLog &log,               ///< [in] log to merge against
    const hobject_t &hoid,               ///< [in] object we are merging
    const mempool::osd_pglog::list<pg_log_entry_t> &orig_entries, ///< [in] entries for hoid to merge
    const pg_info_t &info,              ///< [in] info for merging entries
    eversion_t olog_can_rollback_to,     ///< [in] rollback boundary of input InedexedLog
    missing_type &missing,               ///< [in,out] missing to adjust, use
    LogEntryHandler *rollbacker,         ///< [in] optional rollbacker object
    const DoutPrefixProvider *dpp        ///< [in] logging provider
    ) {
    ldpp_dout(dpp, 20) << __func__ << ": merging hoid " << hoid
		       << " entries: " << orig_entries << dendl;

    if (hoid > info.last_backfill) {
      ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid << " after last_backfill"
			 << dendl;
      return;
    }

    // entries is non-empty
    ceph_assert(!orig_entries.empty());
    // strip out and ignore ERROR entries
    mempool::osd_pglog::list<pg_log_entry_t> entries;
    eversion_t last;
    bool seen_non_error = false;
    for (auto i = orig_entries.begin();
	 i != orig_entries.end();
	 ++i) {
      // all entries are on hoid
      ceph_assert(i->soid == hoid);
      // did not see error entries before this entry and this entry is not error
      // then this entry is the first non error entry
      bool first_non_error = ! seen_non_error && ! i->is_error();
      if (! i->is_error() ) {
        // see a non error entry now
        seen_non_error = true;
      }
      
      // No need to check the first entry since it prior_version is unavailable
      // in the std::list
      // No need to check if the prior_version is the minimal version
      // No need to check the first non-error entry since the leading error
      // entries are not its prior version
      if (i != orig_entries.begin() && i->prior_version != eversion_t() &&
          ! first_non_error) {
	// in increasing order of version
	ceph_assert(i->version > last);
	// prior_version correct (unless it is an ERROR entry)
	ceph_assert(i->prior_version == last || i->is_error());
      }
      if (i->is_error()) {
	ldpp_dout(dpp, 20) << __func__ << ": ignoring " << *i << dendl;
      } else {
	ldpp_dout(dpp, 20) << __func__ << ": keeping " << *i << dendl;
	entries.push_back(*i);
	last = i->version;
      }
    }
    if (entries.empty()) {
      ldpp_dout(dpp, 10) << __func__ << ": no non-ERROR entries" << dendl;
      return;
    }

    const eversion_t prior_version = entries.begin()->prior_version;
    const eversion_t first_divergent_update = entries.begin()->version;
    const eversion_t last_divergent_update = entries.rbegin()->version;
    const bool object_not_in_store =
      !missing.is_missing(hoid) &&
      entries.rbegin()->is_delete();
    ldpp_dout(dpp, 10) << __func__ << ": hoid " << " object_not_in_store: "
                       << object_not_in_store << dendl;
    ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
		       << " prior_version: " << prior_version
		       << " first_divergent_update: " << first_divergent_update
		       << " last_divergent_update: " << last_divergent_update
		       << dendl;

    auto objiter = log.objects.find(hoid);
    if (objiter != log.objects.end() &&
	objiter->second->version >= first_divergent_update) {
      /// Case 1)
      ldpp_dout(dpp, 10) << __func__ << ": more recent entry found: "
			 << *objiter->second << ", already merged" << dendl;

      ceph_assert(objiter->second->version > last_divergent_update);

      // ensure missing has been updated appropriately
      if (objiter->second->is_update() ||
	  (missing.may_include_deletes && objiter->second->is_delete())) {
	ceph_assert(missing.is_missing(hoid) &&
	       missing.get_items().at(hoid).need == objiter->second->version);
      } else {
	ceph_assert(!missing.is_missing(hoid));
      }
      missing.revise_have(hoid, eversion_t());
      missing.mark_fully_dirty(hoid);
      if (rollbacker) {
	if (!object_not_in_store) {
	  rollbacker->remove(hoid);
	}
	for (auto &&i: entries) {
	  rollbacker->trim(i);
	}
      }
      return;
    }

    ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
		       <<" has no more recent entries in log" << dendl;
    if (prior_version == eversion_t() || entries.front().is_clone()) {
      /// Case 2)
      ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			 << " prior_version or op type indicates creation,"
			 << " deleting"
			 << dendl;
      if (missing.is_missing(hoid))
	missing.rm(missing.get_items().find(hoid));
      if (rollbacker) {
	if (!object_not_in_store) {
	  rollbacker->remove(hoid);
	}
	for (auto &&i: entries) {
	  rollbacker->trim(i);
	}
      }
      return;
    }

    if (missing.is_missing(hoid)) {
      /// Case 3)
      ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			 << " missing, " << missing.get_items().at(hoid)
			 << " adjusting" << dendl;

      if (missing.get_items().at(hoid).have == prior_version) {
	ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			   << " missing.have is prior_version " << prior_version
			   << " removing from missing" << dendl;
	missing.rm(missing.get_items().find(hoid));
      } else {
	ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			   << " missing.have is " << missing.get_items().at(hoid).have
			   << ", adjusting" << dendl;
	missing.revise_need(hoid, prior_version, false);
	if (prior_version <= info.log_tail) {
	  ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			     << " prior_version " << prior_version
			     << " <= info.log_tail "
			     << info.log_tail << dendl;
	}
      }
      if (rollbacker) {
	for (auto &&i: entries) {
	  rollbacker->trim(i);
	}
      }
      return;
    }

    ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
		       << " must be rolled back or recovered,"
		       << " attempting to rollback"
		       << dendl;
    bool can_rollback = true;
    // We are going to make an important decision based on the
    // olog_can_rollback_to value we have received, better known it.
    ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
                       << " olog_can_rollback_to: "
                       << olog_can_rollback_to << dendl;
    /// Distinguish between 4) and 5)
    for (auto i = entries.rbegin(); i != entries.rend(); ++i) {
      if (!i->can_rollback() || i->version <= olog_can_rollback_to) {
	ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid << " cannot rollback "
			   << *i << dendl;
	can_rollback = false;
	break;
      }
    }

    if (can_rollback) {
      /// Case 4)
      for (auto i = entries.rbegin(); i != entries.rend(); ++i) {
	ceph_assert(i->can_rollback() && i->version > olog_can_rollback_to);
	ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			   << " rolling back " << *i << dendl;
	if (rollbacker)
	  rollbacker->rollback(*i);
      }
      ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			 << " rolled back" << dendl;
      return;
    } else {
      /// Case 5)
      ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid << " cannot roll back, "
			 << "removing and adding to missing" << dendl;
      if (rollbacker) {
	if (!object_not_in_store)
	  rollbacker->remove(hoid);
	for (auto &&i: entries) {
	  rollbacker->trim(i);
	}
      }
      missing.add(hoid, prior_version, eversion_t(), false);
      if (prior_version <= info.log_tail) {
	ldpp_dout(dpp, 10) << __func__ << ": hoid " << hoid
			   << " prior_version " << prior_version
			   << " <= info.log_tail "
			   << info.log_tail << dendl;
      }
    }
  }

  /// Merge all entries using above
  template <typename missing_type>
  static void _merge_divergent_entries(
    const IndexedLog &log,               ///< [in] log to merge against
    mempool::osd_pglog::list<pg_log_entry_t> &entries,       ///< [in] entries to merge
    const pg_info_t &oinfo,              ///< [in] info for merging entries
    eversion_t olog_can_rollback_to,     ///< [in] rollback boundary of input IndexedLog
    missing_type &omissing,              ///< [in,out] missing to adjust, use
    LogEntryHandler *rollbacker,         ///< [in] optional rollbacker object
    const DoutPrefixProvider *dpp        ///< [in] logging provider
    ) {
    std::map<hobject_t, mempool::osd_pglog::list<pg_log_entry_t> > split;
    split_by_object(entries, &split);
    for (auto i = split.begin(); i != split.end(); ++i) {
      _merge_object_divergent_entries(
	log,
	i->first,
	i->second,
	oinfo,
	olog_can_rollback_to,
	omissing,
	rollbacker,
	dpp);
    }
  }

  /**
   * Exists for use in TestPGLog for simply testing single divergent log
   * cases
   */
  void merge_old_entry(
    ObjectStore::Transaction& t,
    const pg_log_entry_t& oe,
    const pg_info_t& info,
    LogEntryHandler *rollbacker) {
    mempool::osd_pglog::list<pg_log_entry_t> entries;
    entries.push_back(oe);
    _merge_object_divergent_entries(
      log,
      oe.soid,
      entries,
      info,
      log.get_can_rollback_to(),
      missing,
      rollbacker,
      this);
  }

  bool merge_log_dups(const pg_log_t& olog);

public:

  void rewind_divergent_log(eversion_t newhead,
                            pg_info_t &info,
                            LogEntryHandler *rollbacker,
                            bool &dirty_info,
                            bool &dirty_big_info);

  void merge_log(pg_info_t &oinfo,
		 pg_log_t&& olog,
		 pg_shard_t from,
		 pg_info_t &info, LogEntryHandler *rollbacker,
		 bool &dirty_info, bool &dirty_big_info);

  template <typename missing_type>
  static bool append_log_entries_update_missing(
    const hobject_t &last_backfill,
    const mempool::osd_pglog::list<pg_log_entry_t> &entries,
    bool maintain_rollback,
    IndexedLog *log,
    missing_type &missing,
    LogEntryHandler *rollbacker,
    const DoutPrefixProvider *dpp) {
    bool invalidate_stats = false;
    if (log && !entries.empty()) {
      ceph_assert(log->head < entries.begin()->version);
    }
    for (auto p = entries.begin(); p != entries.end(); ++p) {
      invalidate_stats = invalidate_stats || !p->is_error();
      if (log) {
	ldpp_dout(dpp, 20) << "update missing, append " << *p << dendl;
	log->add(*p);
      }
      if (p->soid <= last_backfill &&
	  !p->is_error()) {
	if (missing.may_include_deletes) {
	  missing.add_next_event(*p);
	} else {
	  if (p->is_delete()) {
	    missing.rm(p->soid, p->version);
	  } else {
	    missing.add_next_event(*p);
	  }
	  if (rollbacker) {
	    // hack to match PG::mark_all_unfound_lost
	    if (maintain_rollback && p->is_lost_delete() && p->can_rollback()) {
	      rollbacker->try_stash(p->soid, p->version.version);
	    } else if (p->is_delete()) {
	      rollbacker->remove(p->soid);
	    }
	  }
	}
      }
    }
    return invalidate_stats;
  }
  bool append_new_log_entries(
    const hobject_t &last_backfill,
    const mempool::osd_pglog::list<pg_log_entry_t> &entries,
    LogEntryHandler *rollbacker) {
    bool invalidate_stats = append_log_entries_update_missing(
      last_backfill,
      entries,
      true,
      &log,
      missing,
      rollbacker,
      this);
    if (!entries.empty()) {
      mark_writeout_from(entries.begin()->version);
      if (entries.begin()->is_lost_delete()) {
	// hack: since lost deletes queue recovery directly, and don't
	// go through activate_not_complete() again, our complete_to
	// iterator may still point at log.end(). Reset it to point
	// before these new lost_delete entries.  This only occurs
	// when lost+delete entries are initially added, which is
	// always in a std::list of solely lost_delete entries, so it is
	// sufficient to check whether the first entry is a
	// lost_delete
	reset_complete_to(nullptr);
      }
    }
    return invalidate_stats;
  }

  void write_log_and_missing(
    ObjectStore::Transaction& t,
    std::map<std::string,ceph::buffer::list> *km,
    const coll_t& coll,
    const ghobject_t &log_oid,
    bool require_rollback);

  static void write_log_and_missing_wo_missing(
    ObjectStore::Transaction& t,
    std::map<std::string,ceph::buffer::list>* km,
    pg_log_t &log,
    const coll_t& coll,
    const ghobject_t &log_oid, std::map<eversion_t, hobject_t> &divergent_priors,
    bool require_rollback,
    const DoutPrefixProvider *dpp = nullptr);

  static void write_log_and_missing(
    ObjectStore::Transaction& t,
    std::map<std::string,ceph::buffer::list>* km,
    pg_log_t &log,
    const coll_t& coll,
    const ghobject_t &log_oid,
    const pg_missing_tracker_t &missing,
    bool require_rollback,
    bool *rebuilt_missing_set_with_deletes,
    const DoutPrefixProvider *dpp = nullptr);

  static void _write_log_and_missing_wo_missing(
    ObjectStore::Transaction& t,
    std::map<std::string,ceph::buffer::list>* km,
    pg_log_t &log,
    const coll_t& coll, const ghobject_t &log_oid,
    std::map<eversion_t, hobject_t> &divergent_priors,
    eversion_t dirty_to,
    eversion_t dirty_from,
    eversion_t writeout_from,
    bool dirty_divergent_priors,
    bool touch_log,
    bool require_rollback,
    eversion_t dirty_to_dups,
    eversion_t dirty_from_dups,
    eversion_t write_from_dups,
    std::set<std::string> *log_keys_debug,
    const DoutPrefixProvider *dpp = nullptr
    );

  static void _write_log_and_missing(
    ObjectStore::Transaction& t,
    std::map<std::string,ceph::buffer::list>* km,
    pg_log_t &log,
    const coll_t& coll, const ghobject_t &log_oid,
    eversion_t dirty_to,
    eversion_t dirty_from,
    eversion_t writeout_from,
    std::set<eversion_t> &&trimmed,
    std::set<std::string> &&trimmed_dups,
    const pg_missing_tracker_t &missing,
    bool touch_log,
    bool require_rollback,
    bool clear_divergent_priors,
    eversion_t dirty_to_dups,
    eversion_t dirty_from_dups,
    eversion_t write_from_dups,
    bool *may_include_deletes_in_missing_dirty,
    std::set<std::string> *log_keys_debug,
    const DoutPrefixProvider *dpp = nullptr
    );

  void read_log_and_missing(
    ObjectStore *store,
    ObjectStore::CollectionHandle& ch,
    ghobject_t pgmeta_oid,
    const pg_info_t &info,
    std::ostringstream &oss,
    bool tolerate_divergent_missing_log,
    bool debug_verify_stored_missing = false
    ) {
    return read_log_and_missing(
      cct, store, ch, pgmeta_oid, info,
      log, missing, oss,
      tolerate_divergent_missing_log,
      &clear_divergent_priors,
      this,
      (pg_log_debug ? &log_keys_debug : nullptr),
      debug_verify_stored_missing);
  }

  template <typename missing_type>
  static void read_log_and_missing(
    CephContext *cct,
    ObjectStore *store,
    ObjectStore::CollectionHandle &ch,
    ghobject_t pgmeta_oid,
    const pg_info_t &info,
    IndexedLog &log,
    missing_type &missing,
    std::ostringstream &oss,
    bool tolerate_divergent_missing_log,
    bool *clear_divergent_priors = nullptr,
    const DoutPrefixProvider *dpp = nullptr,
    std::set<std::string> *log_keys_debug = nullptr,
    bool debug_verify_stored_missing = false
    ) {
    ldpp_dout(dpp, 10) << "read_log_and_missing coll " << ch->cid
		       << " " << pgmeta_oid << dendl;
    size_t total_dups = 0;

    // legacy?
    struct stat st;
    int r = store->stat(ch, pgmeta_oid, &st);
    ceph_assert(r == 0);
    ceph_assert(st.st_size == 0);

    // will get overridden below if it had been recorded
    eversion_t on_disk_can_rollback_to = info.last_update;
    eversion_t on_disk_rollback_info_trimmed_to = eversion_t();
    ObjectMap::ObjectMapIterator p = store->get_omap_iterator(ch,
							      pgmeta_oid);
    std::map<eversion_t, hobject_t> divergent_priors;
    bool must_rebuild = false;
    missing.may_include_deletes = false;
    std::list<pg_log_entry_t> entries;
    std::list<pg_log_dup_t> dups;
    const auto NUM_DUPS_WARN_THRESHOLD = 2*cct->_conf->osd_pg_log_dups_tracked;
    if (p) {
      using ceph::decode;
      for (p->seek_to_first(); p->valid() ; p->next()) {
	// non-log pgmeta_oid keys are prefixed with _; skip those
	if (p->key()[0] == '_')
	  continue;
	auto bl = p->value();//Copy ceph::buffer::list before creating iterator
	auto bp = bl.cbegin();
	if (p->key() == "divergent_priors") {
	  decode(divergent_priors, bp);
	  ldpp_dout(dpp, 20) << "read_log_and_missing " << divergent_priors.size()
			     << " divergent_priors" << dendl;
	  must_rebuild = true;
	  debug_verify_stored_missing = false;
	} else if (p->key() == "can_rollback_to") {
	  decode(on_disk_can_rollback_to, bp);
	} else if (p->key() == "rollback_info_trimmed_to") {
	  decode(on_disk_rollback_info_trimmed_to, bp);
	} else if (p->key() == "may_include_deletes_in_missing") {
	  missing.may_include_deletes = true;
	} else if (p->key().substr(0, 7) == std::string("missing")) {
	  hobject_t oid;
	  pg_missing_item item;
	  decode(oid, bp);
	  decode(item, bp);
          ldpp_dout(dpp, 20) << "read_log_and_missing " << item << dendl;
	  if (item.is_delete()) {
	    ceph_assert(missing.may_include_deletes);
	  }
	  missing.add(oid, std::move(item));
	} else if (p->key().substr(0, 4) == std::string("dup_")) {
	  ++total_dups;
	  pg_log_dup_t dup;
	  decode(dup, bp);
	  if (!dups.empty()) {
	    ceph_assert(dups.back().version < dup.version);
	  }
	  if (dups.size() == NUM_DUPS_WARN_THRESHOLD) {
	    ldpp_dout(dpp, 0) << "read_log_and_missing WARN num of dups exceeded "
			      << NUM_DUPS_WARN_THRESHOLD << "."
			      << " You can be hit by THE DUPS BUG"
			      << " https://tracker.ceph.com/issues/53729."
			      << " Consider ceph-objectstore-tool --op trim-pg-log-dups"
			      << dendl;
	  }
	  dups.push_back(dup);
	} else {
	  pg_log_entry_t e;
	  e.decode_with_checksum(bp);
	  ldpp_dout(dpp, 20) << "read_log_and_missing " << e << dendl;
	  if (!entries.empty()) {
	    pg_log_entry_t last_e(entries.back());
	    ceph_assert(last_e.version.version < e.version.version);
	    ceph_assert(last_e.version.epoch <= e.version.epoch);
	  }
	  entries.push_back(e);
	  if (log_keys_debug)
	    log_keys_debug->insert(e.get_key_name());
	}
      }
    }
    log = IndexedLog(
      info.last_update,
      info.log_tail,
      on_disk_can_rollback_to,
      on_disk_rollback_info_trimmed_to,
      std::move(entries),
      std::move(dups));

    if (must_rebuild || debug_verify_stored_missing) {
      // build missing
      if (debug_verify_stored_missing || info.last_complete < info.last_update) {
	ldpp_dout(dpp, 10)
	  << "read_log_and_missing checking for missing items over interval ("
	  << info.last_complete
	  << "," << info.last_update << "]" << dendl;

	std::set<hobject_t> did;
	std::set<hobject_t> checked;
	std::set<hobject_t> skipped;
	for (auto i = log.log.rbegin(); i != log.log.rend(); ++i) {
	  if (i->soid > info.last_backfill)
	    continue;
	  if (i->is_error())
	    continue;
	  if (did.count(i->soid)) continue;
	  did.insert(i->soid);

	  if (!missing.may_include_deletes && i->is_delete())
	    continue;

	  ceph::buffer::list bv;
	  int r = store->getattr(
	    ch,
	    ghobject_t(i->soid, ghobject_t::NO_GEN, info.pgid.shard),
	    OI_ATTR,
	    bv);
	  if (r >= 0) {
	    object_info_t oi(bv);
	    if (oi.version < i->version) {
	      ldpp_dout(dpp, 15) << "read_log_and_missing  missing " << *i
                           << " (have " << oi.version << ")"
                           << " clean_regions " << i->clean_regions << dendl;

	      if (debug_verify_stored_missing) {
		auto miter = missing.get_items().find(i->soid);
		ceph_assert(miter != missing.get_items().end());
		ceph_assert(miter->second.need == i->version);
		// the 'have' version is reset if an object is deleted,
		// then created again
		ceph_assert(miter->second.have == oi.version || miter->second.have == eversion_t());
		checked.insert(i->soid);
	      } else {
		missing.add(i->soid, i->version, oi.version, i->is_delete());
	      }
	    }
	  } else {
	    ldpp_dout(dpp, 15) << "read_log_and_missing  missing " << *i << dendl;
	    if (debug_verify_stored_missing) {
	      auto miter = missing.get_items().find(i->soid);
	      if (i->is_delete()) {
		ceph_assert(miter == missing.get_items().end() ||
		       (miter->second.need == i->version &&
			miter->second.have == eversion_t()));
	      } else {
		ceph_assert(miter != missing.get_items().end());
		ceph_assert(miter->second.need == i->version);
		ceph_assert(miter->second.have == eversion_t());
	      }
	      checked.insert(i->soid);
	    } else {
	      missing.add(i->soid, i->version, eversion_t(), i->is_delete());
	    }
	  }
	}
	if (debug_verify_stored_missing) {
	  for (auto &&i: missing.get_items()) {
	    if (checked.count(i.first))
	      continue;
	    if (i.first > info.last_backfill) {
	      ldpp_dout(dpp, -1) << __func__ << ": invalid missing std::set entry "
				<< "found before last_backfill: "
				<< i.first << " " << i.second
				<< " last_backfill = " << info.last_backfill
				<< dendl;
	      ceph_abort_msg("invalid missing std::set entry found");
	    }
	    ceph::buffer::list bv;
	    int r = store->getattr(
	      ch,
	      ghobject_t(i.first, ghobject_t::NO_GEN, info.pgid.shard),
	      OI_ATTR,
	      bv);
	    if (r >= 0) {
	      object_info_t oi(bv);
	      ceph_assert(oi.version == i.second.have || eversion_t() == i.second.have);
	    } else {
	      ceph_assert(i.second.is_delete() || eversion_t() == i.second.have);
	    }
	  }
	} else {
	  ceph_assert(must_rebuild);
	  for (auto i = divergent_priors.rbegin();
	       i != divergent_priors.rend();
	       ++i) {
	    if (i->first <= info.last_complete) break;
	    if (i->second > info.last_backfill)
	      continue;
	    if (did.count(i->second)) continue;
	    did.insert(i->second);
	    ceph::buffer::list bv;
	    int r = store->getattr(
	      ch,
	      ghobject_t(i->second, ghobject_t::NO_GEN, info.pgid.shard),
	      OI_ATTR,
	      bv);
	    if (r >= 0) {
	      object_info_t oi(bv);
	      /**
		 * 1) we see this entry in the divergent priors mapping
		 * 2) we didn't see an entry for this object in the log
		 *
		 * From 1 & 2 we know that either the object does not exist
		 * or it is at the version specified in the divergent_priors
		 * map since the object would have been deleted atomically
		 * with the addition of the divergent_priors entry, an older
		 * version would not have been recovered, and a newer version
		 * would show up in the log above.
		 */
	      /**
		 * Unfortunately the assessment above is incorrect because of
		 * http://tracker.ceph.com/issues/17916 (we were incorrectly
		 * not removing the divergent_priors std::set from disk state!),
		 * so let's check that.
		 */
	      if (oi.version > i->first && tolerate_divergent_missing_log) {
		ldpp_dout(dpp, 0) << "read_log divergent_priors entry (" << *i
				  << ") inconsistent with disk state (" <<  oi
				  << "), assuming it is tracker.ceph.com/issues/17916"
				  << dendl;
	      } else {
		ceph_assert(oi.version == i->first);
	      }
	    } else {
	      ldpp_dout(dpp, 15) << "read_log_and_missing  missing " << *i << dendl;
	      missing.add(i->second, i->first, eversion_t(), false);
	    }
	  }
	}
	if (clear_divergent_priors)
	  (*clear_divergent_priors) = true;
      }
    }

    if (!must_rebuild) {
      if (clear_divergent_priors)
	(*clear_divergent_priors) = false;
      missing.flush();
    }
    ldpp_dout(dpp, 10) << "read_log_and_missing done coll " << ch->cid
		       << " total_dups=" << total_dups
		       << " log.dups.size()=" << log.dups.size() << dendl;
  } // static read_log_and_missing

#ifdef WITH_SEASTAR
  seastar::future<> read_log_and_missing_crimson(
    crimson::os::FuturizedStore &store,
    crimson::os::CollectionRef ch,
    const pg_info_t &info,
    ghobject_t pgmeta_oid
    ) {
    return read_log_and_missing_crimson(
      store, ch, info,
      log, (pg_log_debug ? &log_keys_debug : nullptr),
      missing, pgmeta_oid, this);
  }

  static seastar::future<> read_log_and_missing_crimson(
    crimson::os::FuturizedStore &store,
    crimson::os::CollectionRef ch,
    const pg_info_t &info,
    IndexedLog &log,
    std::set<std::string>* log_keys_debug,
    pg_missing_tracker_t &missing,
    ghobject_t pgmeta_oid,
    const DoutPrefixProvider *dpp = nullptr);

#endif

}; // struct PGLog