Whamcloud - gitweb
edffbe4b6aa6797c883df6c10af73522affbf2c2
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_scrub.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2012, 2013, Intel Corporation.
24  */
25 /*
26  * lustre/osd-ldiskfs/osd_scrub.c
27  *
28  * Top-level entry points into osd module
29  *
30  * The OI scrub is used for rebuilding Object Index files when restores MDT from
31  * file-level backup.
32  *
33  * The otable based iterator scans ldiskfs inode table to feed up layer LFSCK.
34  *
35  * Author: Fan Yong <yong.fan@whamcloud.com>
36  */
37
38 #define DEBUG_SUBSYSTEM S_LFSCK
39
40 #include <lustre/lustre_idl.h>
41 #include <lustre_disk.h>
42 #include <dt_object.h>
43 #include <linux/xattr.h>
44
45 #include "osd_internal.h"
46 #include "osd_oi.h"
47 #include "osd_scrub.h"
48
49 #define HALF_SEC        (HZ >> 1)
50
51 #define OSD_OTABLE_MAX_HASH             0x00000000ffffffffULL
52
53 #define SCRUB_NEXT_BREAK        1 /* exit current loop and process next group */
54 #define SCRUB_NEXT_CONTINUE     2 /* skip current object and process next bit */
55 #define SCRUB_NEXT_EXIT         3 /* exit all the loops */
56 #define SCRUB_NEXT_WAIT         4 /* wait for free cache slot */
57 #define SCRUB_NEXT_CRASH        5 /* simulate system crash during OI scrub */
58 #define SCRUB_NEXT_FATAL        6 /* simulate failure during OI scrub */
59 #define SCRUB_NEXT_NOSCRUB      7 /* new created object, no scrub on it */
60 #define SCRUB_NEXT_NOLMA        8 /* the inode has no FID-in-LMA */
61 #define SCRUB_NEXT_OSTOBJ       9 /* for OST-object */
62 #define SCRUB_NEXT_OSTOBJ_OLD   10 /* old OST-object, no LMA or no FID-on-OST
63                                     * flags in LMA */
64
65 /* misc functions */
66
67 static inline struct osd_device *osd_scrub2dev(struct osd_scrub *scrub)
68 {
69         return container_of0(scrub, struct osd_device, od_scrub);
70 }
71
72 static inline struct super_block *osd_scrub2sb(struct osd_scrub *scrub)
73 {
74         return osd_sb(osd_scrub2dev(scrub));
75 }
76
77 static inline int osd_scrub_has_window(struct osd_scrub *scrub,
78                                        struct osd_otable_cache *ooc)
79 {
80         return scrub->os_pos_current < ooc->ooc_pos_preload + SCRUB_WINDOW_SIZE;
81 }
82
83 static inline const char *osd_scrub2name(struct osd_scrub *scrub)
84 {
85         return LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name;
86 }
87
88 /**
89  * update/insert/delete the specified OI mapping (@fid @id) according to the ops
90  *
91  * \retval   1, changed nothing
92  * \retval   0, changed successfully
93  * \retval -ve, on error
94  */
95 static int osd_scrub_refresh_mapping(struct osd_thread_info *info,
96                                      struct osd_device *dev,
97                                      const struct lu_fid *fid,
98                                      const struct osd_inode_id *id,
99                                      int ops, bool force,
100                                      enum oi_check_flags flags)
101 {
102         handle_t *th;
103         int       rc;
104         ENTRY;
105
106         if (dev->od_scrub.os_file.sf_param & SP_DRYRUN && !force)
107                 RETURN(0);
108
109         /* DTO_INDEX_INSERT is enough for other two ops:
110          * delete/update, but save stack. */
111         th = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC,
112                                 osd_dto_credits_noquota[DTO_INDEX_INSERT]);
113         if (IS_ERR(th)) {
114                 rc = PTR_ERR(th);
115                 CDEBUG(D_LFSCK, "%s: fail to start trans for scrub op %d "
116                        DFID" => %u/%u: rc = %d\n", osd_name(dev), ops,
117                        PFID(fid), id->oii_ino, id->oii_gen, rc);
118                 RETURN(rc);
119         }
120
121         switch (ops) {
122         case DTO_INDEX_UPDATE:
123                 rc = osd_oi_update(info, dev, fid, id, th, flags);
124                 if (unlikely(rc == -ENOENT)) {
125                         /* Some unlink thread may removed the OI mapping. */
126                         rc = 1;
127                 }
128                 break;
129         case DTO_INDEX_INSERT:
130                 rc = osd_oi_insert(info, dev, fid, id, th, flags);
131                 if (unlikely(rc == -EEXIST)) {
132                         rc = 1;
133                         /* XXX: There are trouble things when adding OI
134                          *      mapping for IGIF object, which may cause
135                          *      multiple objects to be mapped to the same
136                          *      IGIF formatted FID. Consider the following
137                          *      situations:
138                          *
139                          *      1) The MDT is upgrading from 1.8 device.
140                          *      The OI scrub generates IGIF FID1 for the
141                          *      OBJ1 and adds the OI mapping.
142                          *
143                          *      2) For some reason, the OI scrub does not
144                          *      process all the IGIF objects completely.
145                          *
146                          *      3) The MDT is backuped and restored against
147                          *      this device.
148                          *
149                          *      4) When the MDT mounts up, the OI scrub will
150                          *      try to rebuild the OI files. For some IGIF
151                          *      object, OBJ2, which was not processed by the
152                          *      OI scrub before the backup/restore, and the
153                          *      new generated IGIF formatted FID may be just
154                          *      the FID1, the same as OBJ1.
155                          *
156                          *      Under such case, the OI scrub cannot know how
157                          *      to generate new FID for the OBJ2.
158                          *
159                          *      Currently, we do nothing for that. One possible
160                          *      solution is to generate new normal FID for the
161                          *      conflict object.
162                          *
163                          *      Anyway, it is rare, only exists in theory. */
164                 }
165                 break;
166         case DTO_INDEX_DELETE:
167                 rc = osd_oi_delete(info, dev, fid, th, flags);
168                 if (rc == -ENOENT) {
169                         /* It is normal that the unlink thread has removed the
170                          * OI mapping already. */
171                         rc = 1;
172                 }
173                 break;
174         default:
175                 LASSERTF(0, "Unexpected ops %d\n", ops);
176                 break;
177         }
178
179         ldiskfs_journal_stop(th);
180         if (rc < 0)
181                 CDEBUG(D_LFSCK, "%s: fail to refresh OI map for scrub op %d "
182                        DFID" => %u/%u: rc = %d\n", osd_name(dev), ops,
183                        PFID(fid), id->oii_ino, id->oii_gen, rc);
184
185         RETURN(rc);
186 }
187
188 /* OI_scrub file ops */
189
190 static void osd_scrub_file_to_cpu(struct scrub_file *des,
191                                   struct scrub_file *src)
192 {
193         memcpy(des->sf_uuid, src->sf_uuid, 16);
194         des->sf_flags   = le64_to_cpu(src->sf_flags);
195         des->sf_magic   = le32_to_cpu(src->sf_magic);
196         des->sf_status  = le16_to_cpu(src->sf_status);
197         des->sf_param   = le16_to_cpu(src->sf_param);
198         des->sf_time_last_complete      =
199                                 le64_to_cpu(src->sf_time_last_complete);
200         des->sf_time_latest_start       =
201                                 le64_to_cpu(src->sf_time_latest_start);
202         des->sf_time_last_checkpoint    =
203                                 le64_to_cpu(src->sf_time_last_checkpoint);
204         des->sf_pos_latest_start        =
205                                 le64_to_cpu(src->sf_pos_latest_start);
206         des->sf_pos_last_checkpoint     =
207                                 le64_to_cpu(src->sf_pos_last_checkpoint);
208         des->sf_pos_first_inconsistent  =
209                                 le64_to_cpu(src->sf_pos_first_inconsistent);
210         des->sf_items_checked           =
211                                 le64_to_cpu(src->sf_items_checked);
212         des->sf_items_updated           =
213                                 le64_to_cpu(src->sf_items_updated);
214         des->sf_items_failed            =
215                                 le64_to_cpu(src->sf_items_failed);
216         des->sf_items_updated_prior     =
217                                 le64_to_cpu(src->sf_items_updated_prior);
218         des->sf_run_time        = le32_to_cpu(src->sf_run_time);
219         des->sf_success_count   = le32_to_cpu(src->sf_success_count);
220         des->sf_oi_count        = le16_to_cpu(src->sf_oi_count);
221         des->sf_internal_flags  = le16_to_cpu(src->sf_internal_flags);
222         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
223 }
224
225 static void osd_scrub_file_to_le(struct scrub_file *des,
226                                  struct scrub_file *src)
227 {
228         memcpy(des->sf_uuid, src->sf_uuid, 16);
229         des->sf_flags   = cpu_to_le64(src->sf_flags);
230         des->sf_magic   = cpu_to_le32(src->sf_magic);
231         des->sf_status  = cpu_to_le16(src->sf_status);
232         des->sf_param   = cpu_to_le16(src->sf_param);
233         des->sf_time_last_complete      =
234                                 cpu_to_le64(src->sf_time_last_complete);
235         des->sf_time_latest_start       =
236                                 cpu_to_le64(src->sf_time_latest_start);
237         des->sf_time_last_checkpoint    =
238                                 cpu_to_le64(src->sf_time_last_checkpoint);
239         des->sf_pos_latest_start        =
240                                 cpu_to_le64(src->sf_pos_latest_start);
241         des->sf_pos_last_checkpoint     =
242                                 cpu_to_le64(src->sf_pos_last_checkpoint);
243         des->sf_pos_first_inconsistent  =
244                                 cpu_to_le64(src->sf_pos_first_inconsistent);
245         des->sf_items_checked           =
246                                 cpu_to_le64(src->sf_items_checked);
247         des->sf_items_updated           =
248                                 cpu_to_le64(src->sf_items_updated);
249         des->sf_items_failed            =
250                                 cpu_to_le64(src->sf_items_failed);
251         des->sf_items_updated_prior     =
252                                 cpu_to_le64(src->sf_items_updated_prior);
253         des->sf_run_time        = cpu_to_le32(src->sf_run_time);
254         des->sf_success_count   = cpu_to_le32(src->sf_success_count);
255         des->sf_oi_count        = cpu_to_le16(src->sf_oi_count);
256         des->sf_internal_flags  = cpu_to_le16(src->sf_internal_flags);
257         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
258 }
259
260 static void osd_scrub_file_init(struct osd_scrub *scrub, __u8 *uuid)
261 {
262         struct scrub_file *sf = &scrub->os_file;
263
264         memset(sf, 0, sizeof(*sf));
265         memcpy(sf->sf_uuid, uuid, 16);
266         sf->sf_magic = SCRUB_MAGIC_V1;
267         sf->sf_status = SS_INIT;
268 }
269
270 void osd_scrub_file_reset(struct osd_scrub *scrub, __u8 *uuid, __u64 flags)
271 {
272         struct scrub_file *sf = &scrub->os_file;
273
274         CDEBUG(D_LFSCK, "%.16s: reset OI scrub file, flags = "LPX64"\n",
275                osd_scrub2name(scrub), flags);
276         memcpy(sf->sf_uuid, uuid, 16);
277         sf->sf_status = SS_INIT;
278         sf->sf_flags |= flags;
279         sf->sf_run_time = 0;
280         sf->sf_time_latest_start = 0;
281         sf->sf_time_last_checkpoint = 0;
282         sf->sf_pos_latest_start = 0;
283         sf->sf_pos_last_checkpoint = 0;
284         sf->sf_pos_first_inconsistent = 0;
285         sf->sf_items_checked = 0;
286         sf->sf_items_updated = 0;
287         sf->sf_items_failed = 0;
288         sf->sf_items_updated_prior = 0;
289         sf->sf_items_noscrub = 0;
290         sf->sf_items_igif = 0;
291 }
292
293 static int osd_scrub_file_load(struct osd_scrub *scrub)
294 {
295         loff_t  pos  = 0;
296         int     len  = sizeof(scrub->os_file_disk);
297         int     rc;
298
299         rc = osd_ldiskfs_read(scrub->os_inode, &scrub->os_file_disk, len, &pos);
300         if (rc == len) {
301                 struct scrub_file *sf = &scrub->os_file;
302
303                 osd_scrub_file_to_cpu(sf, &scrub->os_file_disk);
304                 if (sf->sf_magic != SCRUB_MAGIC_V1) {
305                         CDEBUG(D_LFSCK, "%.16s: invalid scrub magic "
306                                "0x%x != 0x%x\n", osd_scrub2name(scrub),
307                                sf->sf_magic, SCRUB_MAGIC_V1);
308                         /* Process it as new scrub file. */
309                         rc = -ENOENT;
310                 } else {
311                         rc = 0;
312                 }
313         } else if (rc != 0) {
314                 CDEBUG(D_LFSCK, "%.16s: fail to load scrub file, "
315                        "expected = %d: rc = %d\n",
316                        osd_scrub2name(scrub), len, rc);
317                 if (rc > 0)
318                         rc = -EFAULT;
319         } else {
320                 /* return -ENOENT for empty scrub file case. */
321                 rc = -ENOENT;
322         }
323
324         return rc;
325 }
326
327 int osd_scrub_file_store(struct osd_scrub *scrub)
328 {
329         struct osd_device *dev;
330         handle_t          *jh;
331         loff_t             pos     = 0;
332         int                len     = sizeof(scrub->os_file_disk);
333         int                credits;
334         int                rc;
335
336         dev = container_of0(scrub, struct osd_device, od_scrub);
337         credits = osd_dto_credits_noquota[DTO_WRITE_BASE] +
338                   osd_dto_credits_noquota[DTO_WRITE_BLOCK];
339         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, credits);
340         if (IS_ERR(jh)) {
341                 rc = PTR_ERR(jh);
342                 CDEBUG(D_LFSCK, "%.16s: fail to start trans for scrub store: "
343                        "rc = %d\n", osd_scrub2name(scrub), rc);
344                 return rc;
345         }
346
347         osd_scrub_file_to_le(&scrub->os_file_disk, &scrub->os_file);
348         rc = osd_ldiskfs_write_record(scrub->os_inode, &scrub->os_file_disk,
349                                       len, 0, &pos, jh);
350         ldiskfs_journal_stop(jh);
351         if (rc != 0)
352                 CDEBUG(D_LFSCK, "%.16s: fail to store scrub file, "
353                        "expected = %d: rc = %d\n",
354                        osd_scrub2name(scrub), len, rc);
355
356         scrub->os_time_last_checkpoint = cfs_time_current();
357         scrub->os_time_next_checkpoint = scrub->os_time_last_checkpoint +
358                                 cfs_time_seconds(SCRUB_CHECKPOINT_INTERVAL);
359         return rc;
360 }
361
362 static int
363 osd_scrub_convert_ff(struct osd_thread_info *info, struct osd_device *dev,
364                      struct inode *inode, const struct lu_fid *fid)
365 {
366         struct filter_fid_old   *ff      = &info->oti_ff;
367         struct dentry           *dentry  = &info->oti_obj_dentry;
368         handle_t                *jh;
369         int                      size    = 0;
370         int                      rc;
371         bool                     removed = false;
372         bool                     reset   = true;
373         ENTRY;
374
375         if (dev->od_scrub.os_file.sf_param & SP_DRYRUN)
376                 RETURN(0);
377
378         /* We want the LMA to fit into the 256-byte OST inode, so operate
379          * as following:
380          * 1) read old XATTR_NAME_FID and save the parent FID;
381          * 2) delete the old XATTR_NAME_FID;
382          * 3) make new LMA and add it;
383          * 4) generate new XATTR_NAME_FID with the saved parent FID and add it.
384          *
385          * Making the LMA to fit into the 256-byte OST inode can save time for
386          * normal osd_check_lma() and for other OI scrub scanning in future.
387          * So it is worth to make some slow conversion here. */
388         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC,
389                                 osd_dto_credits_noquota[DTO_XATTR_SET] * 3);
390         if (IS_ERR(jh)) {
391                 rc = PTR_ERR(jh);
392                 CDEBUG(D_LFSCK, "%s: fail to start trans for convert ff "
393                        DFID": rc = %d\n", osd_name(dev), PFID(fid), rc);
394                 RETURN(rc);
395         }
396
397         /* 1) read old XATTR_NAME_FID and save the parent FID */
398         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
399         if (rc == sizeof(*ff)) {
400                 /* 2) delete the old XATTR_NAME_FID */
401                 ll_vfs_dq_init(inode);
402                 rc = inode->i_op->removexattr(dentry, XATTR_NAME_FID);
403                 if (rc != 0)
404                         GOTO(stop, rc);
405
406                 removed = true;
407         } else if (unlikely(rc == -ENODATA)) {
408                 reset = false;
409         } else if (rc != sizeof(struct filter_fid)) {
410                 GOTO(stop, rc = -EINVAL);
411         }
412
413         /* 3) make new LMA and add it */
414         rc = osd_ea_fid_set(info, inode, fid, LMAC_FID_ON_OST, 0);
415         if (rc == 0 && reset)
416                 size = sizeof(struct filter_fid);
417         else if (rc != 0 && removed)
418                 /* If failed, we should try to add the old back. */
419                 size = sizeof(struct filter_fid_old);
420
421         /* 4) generate new XATTR_NAME_FID with the saved parent FID and add it*/
422         if (size > 0) {
423                 int rc1;
424
425                 rc1 = __osd_xattr_set(info, inode, XATTR_NAME_FID, ff, size,
426                                       XATTR_CREATE);
427                 if (rc1 != 0 && rc == 0)
428                         rc = rc1;
429         }
430
431         GOTO(stop, rc);
432
433 stop:
434         ldiskfs_journal_stop(jh);
435         if (rc < 0)
436                 CDEBUG(D_LFSCK, "%s: fail to convert ff "DFID": rc = %d\n",
437                        osd_name(dev), PFID(fid), rc);
438         return rc;
439 }
440
441 static int
442 osd_scrub_check_update(struct osd_thread_info *info, struct osd_device *dev,
443                        struct osd_idmap_cache *oic, int val)
444 {
445         struct osd_scrub             *scrub  = &dev->od_scrub;
446         struct scrub_file            *sf     = &scrub->os_file;
447         struct lu_fid                *fid    = &oic->oic_fid;
448         struct osd_inode_id          *lid    = &oic->oic_lid;
449         struct osd_inode_id          *lid2   = &info->oti_id;
450         struct osd_inconsistent_item *oii    = NULL;
451         struct inode                 *inode  = NULL;
452         int                           ops    = DTO_INDEX_UPDATE;
453         int                           idx;
454         int                           rc;
455         bool                          converted = false;
456         ENTRY;
457
458         down_write(&scrub->os_rwsem);
459         scrub->os_new_checked++;
460         if (val < 0)
461                 GOTO(out, rc = val);
462
463         if (scrub->os_in_prior)
464                 oii = list_entry(oic, struct osd_inconsistent_item,
465                                  oii_cache);
466
467         if (lid->oii_ino < sf->sf_pos_latest_start && oii == NULL)
468                 GOTO(out, rc = 0);
469
470         if (fid_is_igif(fid))
471                 sf->sf_items_igif++;
472
473         if (val == SCRUB_NEXT_OSTOBJ_OLD) {
474                 inode = osd_iget(info, dev, lid);
475                 if (IS_ERR(inode)) {
476                         rc = PTR_ERR(inode);
477                         /* Someone removed the inode. */
478                         if (rc == -ENOENT || rc == -ESTALE)
479                                 rc = 0;
480                         GOTO(out, rc);
481                 }
482
483                 sf->sf_flags |= SF_UPGRADE;
484                 sf->sf_internal_flags &= ~SIF_NO_HANDLE_OLD_FID;
485                 dev->od_check_ff = 1;
486                 rc = osd_scrub_convert_ff(info, dev, inode, fid);
487                 if (rc != 0)
488                         GOTO(out, rc);
489
490                 converted = true;
491         }
492
493         if ((val == SCRUB_NEXT_NOLMA) &&
494             (!scrub->os_convert_igif || OBD_FAIL_CHECK(OBD_FAIL_FID_NOLMA)))
495                 GOTO(out, rc = 0);
496
497         if ((oii != NULL && oii->oii_insert) || (val == SCRUB_NEXT_NOLMA))
498                 goto iget;
499
500         rc = osd_oi_lookup(info, dev, fid, lid2,
501                 (val == SCRUB_NEXT_OSTOBJ ||
502                  val == SCRUB_NEXT_OSTOBJ_OLD) ? OI_KNOWN_ON_OST : 0);
503         if (rc != 0) {
504                 if (rc != -ENOENT && rc != -ESTALE)
505                         GOTO(out, rc);
506
507 iget:
508                 if (inode == NULL) {
509                         inode = osd_iget(info, dev, lid);
510                         if (IS_ERR(inode)) {
511                                 rc = PTR_ERR(inode);
512                                 /* Someone removed the inode. */
513                                 if (rc == -ENOENT || rc == -ESTALE)
514                                         rc = 0;
515                                 GOTO(out, rc);
516                         }
517                 }
518
519                 scrub->os_full_speed = 1;
520                 ops = DTO_INDEX_INSERT;
521                 idx = osd_oi_fid2idx(dev, fid);
522                 switch (val) {
523                 case SCRUB_NEXT_NOLMA:
524                         sf->sf_flags |= SF_UPGRADE;
525                         if (!(sf->sf_param & SP_DRYRUN)) {
526                                 rc = osd_ea_fid_set(info, inode, fid, 0, 0);
527                                 if (rc != 0)
528                                         GOTO(out, rc);
529                         }
530
531                         if (!(sf->sf_flags & SF_INCONSISTENT))
532                                 dev->od_igif_inoi = 0;
533                         break;
534                 case SCRUB_NEXT_OSTOBJ:
535                         sf->sf_flags |= SF_INCONSISTENT;
536                 case SCRUB_NEXT_OSTOBJ_OLD:
537                         break;
538                 default:
539                         sf->sf_flags |= SF_RECREATED;
540                         if (unlikely(!ldiskfs_test_bit(idx, sf->sf_oi_bitmap)))
541                                 ldiskfs_set_bit(idx, sf->sf_oi_bitmap);
542                         break;
543                 }
544         } else if (osd_id_eq(lid, lid2)) {
545                 if (converted)
546                         sf->sf_items_updated++;
547
548                 GOTO(out, rc = 0);
549         } else {
550                 scrub->os_full_speed = 1;
551                 sf->sf_flags |= SF_INCONSISTENT;
552
553                 /* XXX: If the device is restored from file-level backup, then
554                  *      some IGIFs may have been already in OI files, and some
555                  *      may be not yet. Means upgrading from 1.8 may be partly
556                  *      processed, but some clients may hold some immobilized
557                  *      IGIFs, and use them to access related objects. Under
558                  *      such case, OSD does not know whether an given IGIF has
559                  *      been processed or to be processed, and it also cannot
560                  *      generate local ino#/gen# directly from the immobilized
561                  *      IGIF because of the backup/restore. Then force OSD to
562                  *      lookup the given IGIF in OI files, and if no entry,
563                  *      then ask the client to retry after upgrading completed.
564                  *      No better choice. */
565                 dev->od_igif_inoi = 1;
566         }
567
568         rc = osd_scrub_refresh_mapping(info, dev, fid, lid, ops, false,
569                         (val == SCRUB_NEXT_OSTOBJ ||
570                          val == SCRUB_NEXT_OSTOBJ_OLD) ? OI_KNOWN_ON_OST : 0);
571         if (rc == 0) {
572                 if (scrub->os_in_prior)
573                         sf->sf_items_updated_prior++;
574                 else
575                         sf->sf_items_updated++;
576
577                 /* The target has been changed, need to be re-loaded. */
578                 lu_object_purge(info->oti_env, osd2lu_dev(dev), fid);
579         }
580
581         GOTO(out, rc);
582
583 out:
584         if (rc < 0) {
585                 sf->sf_items_failed++;
586                 if (sf->sf_pos_first_inconsistent == 0 ||
587                     sf->sf_pos_first_inconsistent > lid->oii_ino)
588                         sf->sf_pos_first_inconsistent = lid->oii_ino;
589         } else {
590                 rc = 0;
591         }
592
593         /* There may be conflict unlink during the OI scrub,
594          * if happend, then remove the new added OI mapping. */
595         if (ops == DTO_INDEX_INSERT && inode != NULL && !IS_ERR(inode) &&
596             unlikely(inode->i_nlink == 0))
597                 osd_scrub_refresh_mapping(info, dev, fid, lid,
598                                 DTO_INDEX_DELETE, false,
599                                 (val == SCRUB_NEXT_OSTOBJ ||
600                                  val == SCRUB_NEXT_OSTOBJ_OLD) ?
601                                 OI_KNOWN_ON_OST : 0);
602         up_write(&scrub->os_rwsem);
603
604         if (inode != NULL && !IS_ERR(inode))
605                 iput(inode);
606
607         if (oii != NULL) {
608                 LASSERT(!list_empty(&oii->oii_list));
609
610                 spin_lock(&scrub->os_lock);
611                 list_del_init(&oii->oii_list);
612                 spin_unlock(&scrub->os_lock);
613                 OBD_FREE_PTR(oii);
614         }
615         RETURN(sf->sf_param & SP_FAILOUT ? rc : 0);
616 }
617
618 /* OI scrub APIs */
619
620 static int osd_scrub_prep(struct osd_device *dev)
621 {
622         struct osd_scrub     *scrub  = &dev->od_scrub;
623         struct ptlrpc_thread *thread = &scrub->os_thread;
624         struct scrub_file    *sf     = &scrub->os_file;
625         __u32                 flags  = scrub->os_start_flags;
626         int                   rc;
627         bool                  drop_dryrun = false;
628         ENTRY;
629
630         down_write(&scrub->os_rwsem);
631         if (flags & SS_SET_FAILOUT)
632                 sf->sf_param |= SP_FAILOUT;
633
634         if (flags & SS_CLEAR_FAILOUT)
635                 sf->sf_param &= ~SP_FAILOUT;
636
637         if (flags & SS_SET_DRYRUN)
638                 sf->sf_param |= SP_DRYRUN;
639
640         if (flags & SS_CLEAR_DRYRUN && sf->sf_param & SP_DRYRUN) {
641                 sf->sf_param &= ~SP_DRYRUN;
642                 drop_dryrun = true;
643         }
644
645         if (flags & SS_RESET)
646                 osd_scrub_file_reset(scrub,
647                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid, 0);
648
649         if (flags & SS_AUTO) {
650                 scrub->os_full_speed = 1;
651                 sf->sf_flags |= SF_AUTO;
652                 /* For the case of OI scrub auto triggered, NOT dryrun. */
653                 sf->sf_param &= ~SP_FAILOUT;
654         } else {
655                 scrub->os_full_speed = 0;
656         }
657
658         if (sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT | SF_UPGRADE))
659                 scrub->os_full_speed = 1;
660
661         scrub->os_in_prior = 0;
662         spin_lock(&scrub->os_lock);
663         scrub->os_waiting = 0;
664         scrub->os_paused = 0;
665         spin_unlock(&scrub->os_lock);
666         scrub->os_new_checked = 0;
667         if (drop_dryrun && sf->sf_pos_first_inconsistent != 0)
668                 sf->sf_pos_latest_start = sf->sf_pos_first_inconsistent;
669         else if (sf->sf_pos_last_checkpoint != 0)
670                 sf->sf_pos_latest_start = sf->sf_pos_last_checkpoint + 1;
671         else
672                 sf->sf_pos_latest_start = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
673
674         scrub->os_pos_current = sf->sf_pos_latest_start;
675         sf->sf_status = SS_SCANNING;
676         sf->sf_time_latest_start = cfs_time_current_sec();
677         sf->sf_time_last_checkpoint = sf->sf_time_latest_start;
678         rc = osd_scrub_file_store(scrub);
679         if (rc == 0) {
680                 spin_lock(&scrub->os_lock);
681                 thread_set_flags(thread, SVC_RUNNING);
682                 spin_unlock(&scrub->os_lock);
683                 wake_up_all(&thread->t_ctl_waitq);
684         }
685         up_write(&scrub->os_rwsem);
686
687         RETURN(rc);
688 }
689
690 static int osd_scrub_checkpoint(struct osd_scrub *scrub)
691 {
692         struct scrub_file *sf = &scrub->os_file;
693         int                rc;
694
695         if (likely(cfs_time_before(cfs_time_current(),
696                                    scrub->os_time_next_checkpoint) ||
697                    scrub->os_new_checked == 0))
698                 return 0;
699
700         down_write(&scrub->os_rwsem);
701         sf->sf_items_checked += scrub->os_new_checked;
702         scrub->os_new_checked = 0;
703         sf->sf_pos_last_checkpoint = scrub->os_pos_current;
704         sf->sf_time_last_checkpoint = cfs_time_current_sec();
705         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
706                                             scrub->os_time_last_checkpoint);
707         rc = osd_scrub_file_store(scrub);
708         up_write(&scrub->os_rwsem);
709
710         return rc;
711 }
712
713 static void osd_scrub_post(struct osd_scrub *scrub, int result)
714 {
715         struct scrub_file *sf = &scrub->os_file;
716         ENTRY;
717
718         down_write(&scrub->os_rwsem);
719         spin_lock(&scrub->os_lock);
720         thread_set_flags(&scrub->os_thread, SVC_STOPPING);
721         spin_unlock(&scrub->os_lock);
722         if (scrub->os_new_checked > 0) {
723                 sf->sf_items_checked += scrub->os_new_checked;
724                 scrub->os_new_checked = 0;
725                 sf->sf_pos_last_checkpoint = scrub->os_pos_current;
726         }
727         sf->sf_time_last_checkpoint = cfs_time_current_sec();
728         if (result > 0) {
729                 struct osd_device *dev =
730                         container_of0(scrub, struct osd_device, od_scrub);
731
732                 dev->od_igif_inoi = 1;
733                 dev->od_check_ff = 0;
734                 sf->sf_status = SS_COMPLETED;
735                 if (!(sf->sf_param & SP_DRYRUN)) {
736                         memset(sf->sf_oi_bitmap, 0, SCRUB_OI_BITMAP_SIZE);
737                         sf->sf_flags &= ~(SF_RECREATED | SF_INCONSISTENT |
738                                           SF_UPGRADE | SF_AUTO);
739                 }
740                 sf->sf_time_last_complete = sf->sf_time_last_checkpoint;
741                 sf->sf_success_count++;
742         } else if (result == 0) {
743                 if (scrub->os_paused)
744                         sf->sf_status = SS_PAUSED;
745                 else
746                         sf->sf_status = SS_STOPPED;
747         } else {
748                 sf->sf_status = SS_FAILED;
749         }
750         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
751                                             scrub->os_time_last_checkpoint);
752         result = osd_scrub_file_store(scrub);
753         up_write(&scrub->os_rwsem);
754
755         EXIT;
756 }
757
758 /* iteration engine */
759
760 struct osd_iit_param {
761         struct super_block *sb;
762         struct buffer_head *bitmap;
763         ldiskfs_group_t bg;
764         __u32 gbase;
765         __u32 offset;
766 };
767
768 typedef int (*osd_iit_next_policy)(struct osd_thread_info *info,
769                                    struct osd_device *dev,
770                                    struct osd_iit_param *param,
771                                    struct osd_idmap_cache **oic,
772                                    int noslot);
773
774 typedef int (*osd_iit_exec_policy)(struct osd_thread_info *info,
775                                    struct osd_device *dev,
776                                    struct osd_iit_param *param,
777                                    struct osd_idmap_cache *oic,
778                                    int *noslot, int rc);
779
780 static int osd_iit_next(struct osd_iit_param *param, __u32 *pos)
781 {
782         param->offset = ldiskfs_find_next_bit(param->bitmap->b_data,
783                         LDISKFS_INODES_PER_GROUP(param->sb), param->offset);
784         if (param->offset >= LDISKFS_INODES_PER_GROUP(param->sb)) {
785                 *pos = 1 + (param->bg+1) * LDISKFS_INODES_PER_GROUP(param->sb);
786                 return SCRUB_NEXT_BREAK;
787         } else {
788                 *pos = param->gbase + param->offset;
789                 return 0;
790         }
791 }
792
793 /**
794  * \retval SCRUB_NEXT_OSTOBJ_OLD: FID-on-OST
795  * \retval 0: FID-on-MDT
796  */
797 static int osd_scrub_check_local_fldb(struct osd_thread_info *info,
798                                       struct osd_device *dev,
799                                       struct lu_fid *fid)
800 {
801         /* XXX: The initial OI scrub will scan the top level /O to generate
802          *      a small local FLDB according to the <seq>. If the given FID
803          *      is in the local FLDB, then it is FID-on-OST; otherwise it's
804          *      quite possible for FID-on-MDT. */
805         if (dev->od_is_ost)
806                 return SCRUB_NEXT_OSTOBJ_OLD;
807         else
808                 return 0;
809 }
810
811 static int osd_scrub_get_fid(struct osd_thread_info *info,
812                              struct osd_device *dev, struct inode *inode,
813                              struct lu_fid *fid, bool scrub)
814 {
815         struct lustre_mdt_attrs *lma     = &info->oti_mdt_attrs;
816         int                      rc;
817         bool                     has_lma = false;
818
819         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
820         if (rc == 0) {
821                 has_lma = true;
822                 if (lma->lma_compat & LMAC_NOT_IN_OI ||
823                     lma->lma_incompat & LMAI_AGENT)
824                         return SCRUB_NEXT_CONTINUE;
825
826                 *fid = lma->lma_self_fid;
827                 if (!scrub)
828                         return 0;
829
830                 if (lma->lma_compat & LMAC_FID_ON_OST)
831                         return SCRUB_NEXT_OSTOBJ;
832
833                 if (fid_is_idif(fid))
834                         return SCRUB_NEXT_OSTOBJ_OLD;
835
836                 /* For local object. */
837                 if (fid_is_internal(fid))
838                         return 0;
839
840                 /* For external visible MDT-object with non-normal FID. */
841                 if (fid_is_namespace_visible(fid) && !fid_is_norm(fid))
842                         return 0;
843
844                 /* For the object with normal FID, it may be MDT-object,
845                  * or may be 2.4 OST-object, need further distinguish.
846                  * Fall through to next section. */
847         }
848
849         if (rc == -ENODATA || rc == 0) {
850                 rc = osd_get_idif(info, inode, &info->oti_obj_dentry, fid);
851                 if (rc == 0) {
852                         if (scrub)
853                                 /* It is old 2.x (x <= 3) or 1.8 OST-object. */
854                                 rc = SCRUB_NEXT_OSTOBJ_OLD;
855                         return rc;
856                 }
857
858                 if (rc > 0) {
859                         if (!has_lma)
860                                 /* It is FID-on-OST, but we do not know how
861                                  * to generate its FID, ignore it directly. */
862                                 rc = SCRUB_NEXT_CONTINUE;
863                         else
864                                 /* It is 2.4 OST-object. */
865                                 rc = SCRUB_NEXT_OSTOBJ_OLD;
866                         return rc;
867                 }
868
869                 if (rc != -ENODATA)
870                         return rc;
871
872                 if (!has_lma) {
873                         if (dev->od_scrub.os_convert_igif) {
874                                 lu_igif_build(fid, inode->i_ino,
875                                               inode->i_generation);
876                                 if (scrub)
877                                         rc = SCRUB_NEXT_NOLMA;
878                                 else
879                                         rc = 0;
880                         } else {
881                                 /* It may be FID-on-OST, or may be FID for
882                                  * non-MDT0, anyway, we do not know how to
883                                  * generate its FID, ignore it directly. */
884                                 rc = SCRUB_NEXT_CONTINUE;
885                         }
886                         return rc;
887                 }
888
889                 /* For OI scrub case only: the object has LMA but has no ff
890                  * (or ff crashed). It may be MDT-object, may be OST-object
891                  * with crashed ff. The last check is local FLDB. */
892                 rc = osd_scrub_check_local_fldb(info, dev, fid);
893         }
894
895         return rc;
896 }
897
898 static int osd_iit_iget(struct osd_thread_info *info, struct osd_device *dev,
899                         struct lu_fid *fid, struct osd_inode_id *lid, __u32 pos,
900                         struct super_block *sb, bool scrub)
901 {
902         struct inode *inode;
903         int           rc;
904         ENTRY;
905
906         osd_id_gen(lid, pos, OSD_OII_NOGEN);
907         inode = osd_iget(info, dev, lid);
908         if (IS_ERR(inode)) {
909                 rc = PTR_ERR(inode);
910                 /* The inode may be removed after bitmap searching, or the
911                  * file is new created without inode initialized yet. */
912                 if (rc == -ENOENT || rc == -ESTALE)
913                         RETURN(SCRUB_NEXT_CONTINUE);
914
915                 CDEBUG(D_LFSCK, "%.16s: fail to read inode, ino# = %u: "
916                        "rc = %d\n", LDISKFS_SB(sb)->s_es->s_volume_name,
917                        pos, rc);
918                 RETURN(rc);
919         }
920
921         if (scrub &&
922             ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB)) {
923                 /* Only skip it for the first OI scrub accessing. */
924                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
925                 GOTO(put, rc = SCRUB_NEXT_NOSCRUB);
926         }
927
928         rc = osd_scrub_get_fid(info, dev, inode, fid, scrub);
929
930         GOTO(put, rc);
931
932 put:
933         iput(inode);
934         return rc;
935 }
936
937 static int osd_scrub_next(struct osd_thread_info *info, struct osd_device *dev,
938                           struct osd_iit_param *param,
939                           struct osd_idmap_cache **oic, int noslot)
940 {
941         struct osd_scrub     *scrub  = &dev->od_scrub;
942         struct ptlrpc_thread *thread = &scrub->os_thread;
943         struct lu_fid        *fid;
944         struct osd_inode_id  *lid;
945         int                   rc;
946
947         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_DELAY) && cfs_fail_val > 0) {
948                 struct l_wait_info lwi;
949
950                 lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val), NULL, NULL);
951                 l_wait_event(thread->t_ctl_waitq,
952                              !list_empty(&scrub->os_inconsistent_items) ||
953                              !thread_is_running(thread),
954                              &lwi);
955         }
956
957         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_CRASH)) {
958                 spin_lock(&scrub->os_lock);
959                 thread_set_flags(thread, SVC_STOPPING);
960                 spin_unlock(&scrub->os_lock);
961                 return SCRUB_NEXT_CRASH;
962         }
963
964         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_FATAL))
965                 return SCRUB_NEXT_FATAL;
966
967         if (unlikely(!thread_is_running(thread)))
968                 return SCRUB_NEXT_EXIT;
969
970         if (!list_empty(&scrub->os_inconsistent_items)) {
971                 struct osd_inconsistent_item *oii;
972
973                 oii = list_entry(scrub->os_inconsistent_items.next,
974                                  struct osd_inconsistent_item, oii_list);
975                 *oic = &oii->oii_cache;
976                 scrub->os_in_prior = 1;
977                 return 0;
978         }
979
980         if (noslot != 0)
981                 return SCRUB_NEXT_WAIT;
982
983         rc = osd_iit_next(param, &scrub->os_pos_current);
984         if (rc != 0)
985                 return rc;
986
987         *oic = &scrub->os_oic;
988         fid = &(*oic)->oic_fid;
989         lid = &(*oic)->oic_lid;
990         rc = osd_iit_iget(info, dev, fid, lid,
991                           scrub->os_pos_current, param->sb, true);
992         return rc;
993 }
994
995 static int osd_preload_next(struct osd_thread_info *info,
996                             struct osd_device *dev, struct osd_iit_param *param,
997                             struct osd_idmap_cache **oic, int noslot)
998 {
999         struct osd_otable_cache *ooc    = &dev->od_otable_it->ooi_cache;
1000         struct osd_scrub        *scrub;
1001         struct ptlrpc_thread    *thread;
1002         int                      rc;
1003
1004         rc = osd_iit_next(param, &ooc->ooc_pos_preload);
1005         if (rc != 0)
1006                 return rc;
1007
1008         scrub = &dev->od_scrub;
1009         thread = &scrub->os_thread;
1010         if (thread_is_running(thread) &&
1011             ooc->ooc_pos_preload >= scrub->os_pos_current)
1012                 return SCRUB_NEXT_EXIT;
1013
1014         rc = osd_iit_iget(info, dev,
1015                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_fid,
1016                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_lid,
1017                           ooc->ooc_pos_preload, param->sb, false);
1018         /* If succeed, it needs to move forward; otherwise up layer LFSCK may
1019          * ignore the failure, so it still need to skip the inode next time. */
1020         ooc->ooc_pos_preload = param->gbase + ++(param->offset);
1021         return rc;
1022 }
1023
1024 static inline int
1025 osd_scrub_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
1026 {
1027         spin_lock(&scrub->os_lock);
1028         if (osd_scrub_has_window(scrub, &it->ooi_cache) ||
1029             !list_empty(&scrub->os_inconsistent_items) ||
1030             it->ooi_waiting || !thread_is_running(&scrub->os_thread))
1031                 scrub->os_waiting = 0;
1032         else
1033                 scrub->os_waiting = 1;
1034         spin_unlock(&scrub->os_lock);
1035
1036         return !scrub->os_waiting;
1037 }
1038
1039 static int osd_scrub_exec(struct osd_thread_info *info, struct osd_device *dev,
1040                           struct osd_iit_param *param,
1041                           struct osd_idmap_cache *oic, int *noslot, int rc)
1042 {
1043         struct l_wait_info       lwi    = { 0 };
1044         struct osd_scrub        *scrub  = &dev->od_scrub;
1045         struct scrub_file       *sf     = &scrub->os_file;
1046         struct ptlrpc_thread    *thread = &scrub->os_thread;
1047         struct osd_otable_it    *it     = dev->od_otable_it;
1048         struct osd_otable_cache *ooc    = it ? &it->ooi_cache : NULL;
1049
1050         switch (rc) {
1051         case SCRUB_NEXT_CONTINUE:
1052                 goto next;
1053         case SCRUB_NEXT_WAIT:
1054                 goto wait;
1055         case SCRUB_NEXT_NOSCRUB:
1056                 down_write(&scrub->os_rwsem);
1057                 scrub->os_new_checked++;
1058                 sf->sf_items_noscrub++;
1059                 up_write(&scrub->os_rwsem);
1060                 goto next;
1061         }
1062
1063         rc = osd_scrub_check_update(info, dev, oic, rc);
1064         if (rc != 0)
1065                 return rc;
1066
1067         rc = osd_scrub_checkpoint(scrub);
1068         if (rc != 0) {
1069                 CDEBUG(D_LFSCK, "%.16s: fail to checkpoint, pos = %u: "
1070                        "rc = %d\n", osd_scrub2name(scrub),
1071                        scrub->os_pos_current, rc);
1072                 /* Continue, as long as the scrub itself can go ahead. */
1073         }
1074
1075         if (scrub->os_in_prior) {
1076                 scrub->os_in_prior = 0;
1077                 return 0;
1078         }
1079
1080 next:
1081         scrub->os_pos_current = param->gbase + ++(param->offset);
1082
1083 wait:
1084         if (it != NULL && it->ooi_waiting && ooc != NULL &&
1085             ooc->ooc_pos_preload < scrub->os_pos_current) {
1086                 spin_lock(&scrub->os_lock);
1087                 it->ooi_waiting = 0;
1088                 wake_up_all(&thread->t_ctl_waitq);
1089                 spin_unlock(&scrub->os_lock);
1090         }
1091
1092         if (scrub->os_full_speed || rc == SCRUB_NEXT_CONTINUE)
1093                 return 0;
1094
1095         if (ooc != NULL && osd_scrub_has_window(scrub, ooc)) {
1096                 *noslot = 0;
1097                 return 0;
1098         }
1099
1100         if (it != NULL)
1101                 l_wait_event(thread->t_ctl_waitq, osd_scrub_wakeup(scrub, it),
1102                              &lwi);
1103
1104         if (ooc != NULL && osd_scrub_has_window(scrub, ooc))
1105                 *noslot = 0;
1106         else
1107                 *noslot = 1;
1108         return 0;
1109 }
1110
1111 static int osd_preload_exec(struct osd_thread_info *info,
1112                             struct osd_device *dev, struct osd_iit_param *param,
1113                             struct osd_idmap_cache *oic, int *noslot, int rc)
1114 {
1115         struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
1116
1117         if (rc == 0) {
1118                 ooc->ooc_cached_items++;
1119                 ooc->ooc_producer_idx = (ooc->ooc_producer_idx + 1) &
1120                                         ~OSD_OTABLE_IT_CACHE_MASK;
1121         }
1122         return rc > 0 ? 0 : rc;
1123 }
1124
1125 #define SCRUB_IT_ALL    1
1126 #define SCRUB_IT_CRASH  2
1127
1128 static int osd_inode_iteration(struct osd_thread_info *info,
1129                                struct osd_device *dev, __u32 max, bool preload)
1130 {
1131         osd_iit_next_policy   next;
1132         osd_iit_exec_policy   exec;
1133         __u32                *pos;
1134         __u32                *count;
1135         struct osd_iit_param  param;
1136         __u32                 limit;
1137         int                   noslot = 0;
1138         int                   rc;
1139         ENTRY;
1140
1141         if (!preload) {
1142                 struct osd_scrub *scrub = &dev->od_scrub;
1143
1144                 next = osd_scrub_next;
1145                 exec = osd_scrub_exec;
1146                 pos = &scrub->os_pos_current;
1147                 count = &scrub->os_new_checked;
1148         } else {
1149                 struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
1150
1151                 next = osd_preload_next;
1152                 exec = osd_preload_exec;
1153                 pos = &ooc->ooc_pos_preload;
1154                 count = &ooc->ooc_cached_items;
1155         }
1156         param.sb = osd_sb(dev);
1157         limit = le32_to_cpu(LDISKFS_SB(param.sb)->s_es->s_inodes_count);
1158
1159         while (*pos <= limit && *count < max) {
1160                 struct osd_idmap_cache *oic = NULL;
1161
1162                 param.bg = (*pos - 1) / LDISKFS_INODES_PER_GROUP(param.sb);
1163                 param.offset = (*pos - 1) % LDISKFS_INODES_PER_GROUP(param.sb);
1164                 param.gbase = 1 + param.bg * LDISKFS_INODES_PER_GROUP(param.sb);
1165                 param.bitmap = ldiskfs_read_inode_bitmap(param.sb, param.bg);
1166                 if (param.bitmap == NULL) {
1167                         CDEBUG(D_LFSCK, "%.16s: fail to read bitmap for %u, "
1168                                "scrub will stop, urgent mode\n",
1169                                LDISKFS_SB(param.sb)->s_es->s_volume_name,
1170                                (__u32)param.bg);
1171                         RETURN(-EIO);
1172                 }
1173
1174                 while (param.offset < LDISKFS_INODES_PER_GROUP(param.sb) &&
1175                        *count < max) {
1176                         rc = next(info, dev, &param, &oic, noslot);
1177                         switch (rc) {
1178                         case SCRUB_NEXT_BREAK:
1179                                 goto next_group;
1180                         case SCRUB_NEXT_EXIT:
1181                                 brelse(param.bitmap);
1182                                 RETURN(0);
1183                         case SCRUB_NEXT_CRASH:
1184                                 brelse(param.bitmap);
1185                                 RETURN(SCRUB_IT_CRASH);
1186                         case SCRUB_NEXT_FATAL:
1187                                 brelse(param.bitmap);
1188                                 RETURN(-EINVAL);
1189                         }
1190
1191                         rc = exec(info, dev, &param, oic, &noslot, rc);
1192                         if (rc != 0) {
1193                                 brelse(param.bitmap);
1194                                 RETURN(rc);
1195                         }
1196                 }
1197
1198 next_group:
1199                 brelse(param.bitmap);
1200         }
1201
1202         if (*pos > limit)
1203                 RETURN(SCRUB_IT_ALL);
1204         RETURN(0);
1205 }
1206
1207 static int osd_otable_it_preload(const struct lu_env *env,
1208                                  struct osd_otable_it *it)
1209 {
1210         struct osd_device       *dev   = it->ooi_dev;
1211         struct osd_scrub        *scrub = &dev->od_scrub;
1212         struct osd_otable_cache *ooc   = &it->ooi_cache;
1213         int                      rc;
1214         ENTRY;
1215
1216         rc = osd_inode_iteration(osd_oti_get(env), dev,
1217                                  OSD_OTABLE_IT_CACHE_SIZE, true);
1218         if (rc == SCRUB_IT_ALL)
1219                 it->ooi_all_cached = 1;
1220
1221         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
1222                 spin_lock(&scrub->os_lock);
1223                 scrub->os_waiting = 0;
1224                 wake_up_all(&scrub->os_thread.t_ctl_waitq);
1225                 spin_unlock(&scrub->os_lock);
1226         }
1227
1228         RETURN(rc < 0 ? rc : ooc->ooc_cached_items);
1229 }
1230
1231 static int osd_scrub_main(void *args)
1232 {
1233         struct lu_env         env;
1234         struct osd_device    *dev    = (struct osd_device *)args;
1235         struct osd_scrub     *scrub  = &dev->od_scrub;
1236         struct ptlrpc_thread *thread = &scrub->os_thread;
1237         int                   rc;
1238         ENTRY;
1239
1240         rc = lu_env_init(&env, LCT_LOCAL);
1241         if (rc != 0) {
1242                 CDEBUG(D_LFSCK, "%.16s: OI scrub fail to init env: rc = %d\n",
1243                        osd_scrub2name(scrub), rc);
1244                 GOTO(noenv, rc);
1245         }
1246
1247         rc = osd_scrub_prep(dev);
1248         if (rc != 0) {
1249                 CDEBUG(D_LFSCK, "%.16s: OI scrub fail to scrub prep: rc = %d\n",
1250                        osd_scrub2name(scrub), rc);
1251                 GOTO(out, rc);
1252         }
1253
1254         if (!scrub->os_full_speed) {
1255                 struct l_wait_info lwi = { 0 };
1256                 struct osd_otable_it *it = dev->od_otable_it;
1257                 struct osd_otable_cache *ooc = &it->ooi_cache;
1258
1259                 l_wait_event(thread->t_ctl_waitq,
1260                              it->ooi_user_ready || !thread_is_running(thread),
1261                              &lwi);
1262                 if (unlikely(!thread_is_running(thread)))
1263                         GOTO(post, rc = 0);
1264
1265                 scrub->os_pos_current = ooc->ooc_pos_preload;
1266         }
1267
1268         CDEBUG(D_LFSCK, "%.16s: OI scrub start, flags = 0x%x, pos = %u\n",
1269                osd_scrub2name(scrub), scrub->os_start_flags,
1270                scrub->os_pos_current);
1271
1272         rc = osd_inode_iteration(osd_oti_get(&env), dev, ~0U, false);
1273         if (unlikely(rc == SCRUB_IT_CRASH))
1274                 GOTO(out, rc = -EINVAL);
1275         GOTO(post, rc);
1276
1277 post:
1278         osd_scrub_post(scrub, rc);
1279         CDEBUG(D_LFSCK, "%.16s: OI scrub: stop, pos = %u: rc = %d\n",
1280                osd_scrub2name(scrub), scrub->os_pos_current, rc);
1281
1282 out:
1283         while (!list_empty(&scrub->os_inconsistent_items)) {
1284                 struct osd_inconsistent_item *oii;
1285
1286                 oii = list_entry(scrub->os_inconsistent_items.next,
1287                                      struct osd_inconsistent_item, oii_list);
1288                 list_del_init(&oii->oii_list);
1289                 OBD_FREE_PTR(oii);
1290         }
1291         lu_env_fini(&env);
1292
1293 noenv:
1294         spin_lock(&scrub->os_lock);
1295         thread_set_flags(thread, SVC_STOPPED);
1296         wake_up_all(&thread->t_ctl_waitq);
1297         spin_unlock(&scrub->os_lock);
1298         return rc;
1299 }
1300
1301 /* initial OI scrub */
1302
1303 typedef int (*scandir_t)(struct osd_thread_info *, struct osd_device *,
1304                          struct dentry *, filldir_t filldir);
1305
1306 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1307                                loff_t offset, __u64 ino, unsigned d_type);
1308 static int osd_ios_lf_fill(void *buf, const char *name, int namelen,
1309                            loff_t offset, __u64 ino, unsigned d_type);
1310 static int osd_ios_dl_fill(void *buf, const char *name, int namelen,
1311                            loff_t offset, __u64 ino, unsigned d_type);
1312
1313 static int
1314 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1315                      struct dentry *dentry, filldir_t filldir);
1316 static int
1317 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1318                   struct dentry *dentry, filldir_t filldir);
1319
1320 static int
1321 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1322                      struct dentry *dentry, filldir_t filldir);
1323
1324 enum osd_lf_flags {
1325         OLF_SCAN_SUBITEMS       = 0x0001,
1326         OLF_HIDE_FID            = 0x0002,
1327         OLF_SHOW_NAME           = 0x0004,
1328         OLF_NO_OI               = 0x0008,
1329 };
1330
1331 struct osd_lf_map {
1332         char            *olm_name;
1333         struct lu_fid    olm_fid;
1334         __u16            olm_flags;
1335         scandir_t        olm_scandir;
1336         filldir_t        olm_filldir;
1337 };
1338
1339 /* Add the new introduced local files in the list in the future. */
1340 static const struct osd_lf_map osd_lf_maps[] = {
1341         /* CATALOGS */
1342         { CATLIST, { FID_SEQ_LOCAL_FILE, LLOG_CATALOGS_OID, 0 }, OLF_SHOW_NAME,
1343                 NULL, NULL },
1344
1345         /* CONFIGS */
1346         { MOUNT_CONFIGS_DIR, { FID_SEQ_LOCAL_FILE, MGS_CONFIGS_OID, 0 },
1347                 OLF_SCAN_SUBITEMS, osd_ios_general_scan,
1348                 osd_ios_varfid_fill },
1349
1350         /* NIDTBL_VERSIONS */
1351         { MGS_NIDTBL_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1352                 osd_ios_general_scan, osd_ios_varfid_fill },
1353
1354         /* PENDING */
1355         { "PENDING", { 0, 0, 0 }, 0, NULL, NULL },
1356
1357         /* ROOT */
1358         { "ROOT", { FID_SEQ_ROOT, 1, 0 },
1359                 OLF_SCAN_SUBITEMS | OLF_HIDE_FID, osd_ios_ROOT_scan, NULL },
1360
1361         /* changelog_catalog */
1362         { CHANGELOG_CATALOG, { 0, 0, 0 }, 0, NULL, NULL },
1363
1364         /* changelog_users */
1365         { CHANGELOG_USERS, { 0, 0, 0 }, 0, NULL, NULL },
1366
1367         /* fld */
1368         { "fld", { FID_SEQ_LOCAL_FILE, FLD_INDEX_OID, 0 }, OLF_SHOW_NAME,
1369                 NULL, NULL },
1370
1371         /* last_rcvd */
1372         { LAST_RCVD, { FID_SEQ_LOCAL_FILE, LAST_RECV_OID, 0 }, OLF_SHOW_NAME,
1373                 NULL, NULL },
1374
1375         /* lfsck_bookmark */
1376         { "lfsck_bookmark", { 0, 0, 0 }, 0, NULL, NULL },
1377
1378         /* lov_objid */
1379         { LOV_OBJID, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OID, 0 }, OLF_SHOW_NAME,
1380                 NULL, NULL },
1381
1382         /* lov_objseq */
1383         { LOV_OBJSEQ, { FID_SEQ_LOCAL_FILE, MDD_LOV_OBJ_OSEQ, 0 },
1384                 OLF_SHOW_NAME, NULL, NULL },
1385
1386         /* quota_master */
1387         { QMT_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1388                 osd_ios_general_scan, osd_ios_varfid_fill },
1389
1390         /* quota_slave */
1391         { QSD_DIR, { 0, 0, 0 }, OLF_SCAN_SUBITEMS,
1392                 osd_ios_general_scan, osd_ios_varfid_fill },
1393
1394         /* seq_ctl */
1395         { "seq_ctl", { FID_SEQ_LOCAL_FILE, FID_SEQ_CTL_OID, 0 },
1396                 OLF_SHOW_NAME, NULL, NULL },
1397
1398         /* seq_srv */
1399         { "seq_srv", { FID_SEQ_LOCAL_FILE, FID_SEQ_SRV_OID, 0 },
1400                 OLF_SHOW_NAME, NULL, NULL },
1401
1402         /* health_check */
1403         { HEALTH_CHECK, { FID_SEQ_LOCAL_FILE, OFD_HEALTH_CHECK_OID, 0 },
1404                 OLF_SHOW_NAME, NULL, NULL },
1405
1406         /* lfsck_namespace */
1407         { "lfsck_namespace", { 0, 0, 0 }, 0, NULL, NULL },
1408
1409         /* OBJECTS, upgrade from old device */
1410         { OBJECTS, { 0, 0, 0 }, OLF_SCAN_SUBITEMS, osd_ios_OBJECTS_scan, NULL },
1411
1412         /* lquota_v2.user, upgrade from old device */
1413         { "lquota_v2.user", { 0, 0, 0 }, 0, NULL, NULL },
1414
1415         /* lquota_v2.group, upgrade from old device */
1416         { "lquota_v2.group", { 0, 0, 0 }, 0, NULL, NULL },
1417
1418         /* LAST_GROUP, upgrade from old device */
1419         { "LAST_GROUP", { FID_SEQ_LOCAL_FILE, OFD_LAST_GROUP_OID, 0 },
1420                 OLF_SHOW_NAME, NULL, NULL },
1421
1422         /* SLAVE_LOG, llog for destroy slave stripes of striped dir */
1423         { "SLAVE_LOG", { FID_SEQ_LOCAL_FILE, SLAVE_LLOG_CATALOGS_OID, 0 },
1424                OLF_SHOW_NAME, NULL, NULL },
1425
1426         /* lost+found */
1427         { "lost+found", { 0, 0, 0 }, OLF_SCAN_SUBITEMS | OLF_NO_OI,
1428                 osd_ios_general_scan, osd_ios_lf_fill },
1429
1430         { NULL, { 0, 0, 0 }, 0, NULL, NULL }
1431 };
1432
1433 /* Add the new introduced files under .lustre/ in the list in the future. */
1434 static const struct osd_lf_map osd_dl_maps[] = {
1435         /* .lustre/fid */
1436         { "fid", { FID_SEQ_DOT_LUSTRE, FID_OID_DOT_LUSTRE_OBF, 0 }, 0,
1437                 NULL, NULL },
1438
1439         /* .lustre/lost+found */
1440         { "lost+found", { FID_SEQ_DOT_LUSTRE, FID_OID_DOT_LUSTRE_LPF, 0 }, 0,
1441                 NULL, NULL },
1442
1443         { NULL, { 0, 0, 0 }, 0, NULL, NULL }
1444 };
1445
1446 struct osd_ios_item {
1447         struct list_head oii_list;
1448         struct dentry   *oii_dentry;
1449         scandir_t        oii_scandir;
1450         filldir_t        oii_filldir;
1451 };
1452
1453 struct osd_ios_filldir_buf {
1454 #ifdef HAVE_DIR_CONTEXT
1455         /* please keep it as first member */
1456         struct dir_context       ctx;
1457 #endif
1458         struct osd_thread_info  *oifb_info;
1459         struct osd_device       *oifb_dev;
1460         struct dentry           *oifb_dentry;
1461 };
1462
1463 static inline struct dentry *
1464 osd_ios_lookup_one_len(const char *name, struct dentry *parent, int namelen)
1465 {
1466         struct dentry *dentry;
1467
1468         dentry = ll_lookup_one_len(name, parent, namelen);
1469         if (!IS_ERR(dentry) && dentry->d_inode == NULL) {
1470                 dput(dentry);
1471                 return ERR_PTR(-ENOENT);
1472         }
1473
1474         return dentry;
1475 }
1476
1477 static int
1478 osd_ios_new_item(struct osd_device *dev, struct dentry *dentry,
1479                  scandir_t scandir, filldir_t filldir)
1480 {
1481         struct osd_ios_item *item;
1482         ENTRY;
1483
1484         OBD_ALLOC_PTR(item);
1485         if (item == NULL)
1486                 RETURN(-ENOMEM);
1487
1488         INIT_LIST_HEAD(&item->oii_list);
1489         item->oii_dentry = dget(dentry);
1490         item->oii_scandir = scandir;
1491         item->oii_filldir = filldir;
1492         list_add_tail(&item->oii_list, &dev->od_ios_list);
1493
1494         RETURN(0);
1495 }
1496
1497 /**
1498  * osd_ios_scan_one() - check/fix LMA FID and OI entry for one inode
1499  *
1500  * The passed \a inode's \a fid is verified against the LMA FID. If the \a fid
1501  * is NULL or is empty the IGIF FID is used. The FID is verified in the OI to
1502  * reference the inode, or fixed if it is missing or references another inode.
1503  */
1504 static int
1505 osd_ios_scan_one(struct osd_thread_info *info, struct osd_device *dev,
1506                  struct inode *inode, const struct lu_fid *fid, int flags)
1507 {
1508         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
1509         struct osd_inode_id     *id     = &info->oti_id;
1510         struct osd_inode_id     *id2    = &info->oti_id2;
1511         struct osd_scrub        *scrub  = &dev->od_scrub;
1512         struct scrub_file       *sf     = &scrub->os_file;
1513         struct lu_fid            tfid;
1514         int                      rc;
1515         ENTRY;
1516
1517         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
1518         if (rc != 0 && rc != -ENODATA) {
1519                 CDEBUG(D_LFSCK, "%s: fail to get lma for init OI scrub: "
1520                        "rc = %d\n", osd_name(dev), rc);
1521
1522                 RETURN(rc);
1523         }
1524
1525         osd_id_gen(id, inode->i_ino, inode->i_generation);
1526         if (rc == -ENODATA) {
1527                 if (fid == NULL || fid_is_zero(fid) || flags & OLF_HIDE_FID)
1528                         lu_igif_build(&tfid, inode->i_ino, inode->i_generation);
1529                 else
1530                         tfid = *fid;
1531                 rc = osd_ea_fid_set(info, inode, &tfid, 0, 0);
1532                 if (rc != 0) {
1533                         CDEBUG(D_LFSCK, "%s: fail to set LMA for init OI "
1534                               "scrub: rc = %d\n", osd_name(dev), rc);
1535
1536                         RETURN(rc);
1537                 }
1538         } else {
1539                 if (lma->lma_compat & LMAC_NOT_IN_OI)
1540                         RETURN(0);
1541
1542                 tfid = lma->lma_self_fid;
1543         }
1544
1545         rc = osd_oi_lookup(info, dev, &tfid, id2, 0);
1546         if (rc != 0) {
1547                 if (rc != -ENOENT)
1548                         RETURN(rc);
1549
1550                 rc = osd_scrub_refresh_mapping(info, dev, &tfid, id,
1551                                                DTO_INDEX_INSERT, true, 0);
1552                 if (rc > 0)
1553                         rc = 0;
1554
1555                 RETURN(rc);
1556         }
1557
1558         if (osd_id_eq_strict(id, id2))
1559                 RETURN(0);
1560
1561         if (!(sf->sf_flags & SF_INCONSISTENT)) {
1562                 osd_scrub_file_reset(scrub,
1563                                      LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1564                                      SF_INCONSISTENT);
1565                 rc = osd_scrub_file_store(scrub);
1566                 if (rc != 0)
1567                         RETURN(rc);
1568         }
1569
1570         rc = osd_scrub_refresh_mapping(info, dev, &tfid, id,
1571                                        DTO_INDEX_UPDATE, true, 0);
1572         if (rc > 0)
1573                 rc = 0;
1574
1575         RETURN(rc);
1576 }
1577
1578 /**
1579  * It scans the /lost+found, and for the OST-object (with filter_fid
1580  * or filter_fid_old), move them back to its proper /O/<seq>/d<x>.
1581  */
1582 static int osd_ios_lf_fill(void *buf, const char *name, int namelen,
1583                            loff_t offset, __u64 ino, unsigned d_type)
1584 {
1585         struct osd_ios_filldir_buf *fill_buf = buf;
1586         struct osd_thread_info     *info     = fill_buf->oifb_info;
1587         struct osd_device          *dev      = fill_buf->oifb_dev;
1588         struct lu_fid              *fid      = &info->oti_fid;
1589         struct osd_scrub           *scrub    = &dev->od_scrub;
1590         struct dentry              *parent   = fill_buf->oifb_dentry;
1591         struct dentry              *child;
1592         struct inode               *dir      = parent->d_inode;
1593         struct inode               *inode;
1594         int                         rc;
1595         ENTRY;
1596
1597         /* skip any '.' started names */
1598         if (name[0] == '.')
1599                 RETURN(0);
1600
1601         scrub->os_lf_scanned++;
1602         child = osd_ios_lookup_one_len(name, parent, namelen);
1603         if (IS_ERR(child)) {
1604                 CDEBUG(D_LFSCK, "%s: cannot lookup child '%.*s': rc = %d\n",
1605                       osd_name(dev), namelen, name, (int)PTR_ERR(child));
1606                 RETURN(0);
1607         }
1608
1609         inode = child->d_inode;
1610         if (S_ISDIR(inode->i_mode)) {
1611                 rc = osd_ios_new_item(dev, child, osd_ios_general_scan,
1612                                       osd_ios_lf_fill);
1613                 if (rc != 0)
1614                         CDEBUG(D_LFSCK, "%s: cannot add child '%.*s': "
1615                               "rc = %d\n", osd_name(dev), namelen, name, rc);
1616                 GOTO(put, rc);
1617         }
1618
1619         if (!S_ISREG(inode->i_mode))
1620                 GOTO(put, rc = 0);
1621
1622         rc = osd_scrub_get_fid(info, dev, inode, fid, true);
1623         if (rc == SCRUB_NEXT_OSTOBJ || rc == SCRUB_NEXT_OSTOBJ_OLD) {
1624                 rc = osd_obj_map_recover(info, dev, dir, child, fid);
1625                 if (rc == 0) {
1626                         CDEBUG(D_LFSCK, "recovered '%.*s' ["DFID"] from "
1627                                "/lost+found.\n", namelen, name, PFID(fid));
1628                         scrub->os_lf_repaired++;
1629                 } else {
1630                         CDEBUG(D_LFSCK, "%s: cannot rename for '%.*s' "
1631                                DFID": rc = %d\n",
1632                                osd_name(dev), namelen, name, PFID(fid), rc);
1633                 }
1634         }
1635
1636         /* XXX: For MDT-objects, we can move them from /lost+found to namespace
1637          *      visible place, such as the /ROOT/.lustre/lost+found, then LFSCK
1638          *      can process them in furtuer. */
1639
1640         GOTO(put, rc);
1641
1642 put:
1643         if (rc < 0)
1644                 scrub->os_lf_failed++;
1645         dput(child);
1646         /* skip the failure to make the scanning to continue. */
1647         return 0;
1648 }
1649
1650 static int osd_ios_varfid_fill(void *buf, const char *name, int namelen,
1651                                loff_t offset, __u64 ino, unsigned d_type)
1652 {
1653         struct osd_ios_filldir_buf *fill_buf = buf;
1654         struct osd_device          *dev      = fill_buf->oifb_dev;
1655         struct dentry              *child;
1656         int                         rc;
1657         ENTRY;
1658
1659         /* skip any '.' started names */
1660         if (name[0] == '.')
1661                 RETURN(0);
1662
1663         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1664         if (IS_ERR(child))
1665                 RETURN(PTR_ERR(child));
1666
1667         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1668                               NULL, 0);
1669         if (rc == 0 && S_ISDIR(child->d_inode->i_mode))
1670                 rc = osd_ios_new_item(dev, child, osd_ios_general_scan,
1671                                       osd_ios_varfid_fill);
1672         dput(child);
1673
1674         RETURN(rc);
1675 }
1676
1677 static int osd_ios_dl_fill(void *buf, const char *name, int namelen,
1678                            loff_t offset, __u64 ino, unsigned d_type)
1679 {
1680         struct osd_ios_filldir_buf *fill_buf = buf;
1681         struct osd_device          *dev      = fill_buf->oifb_dev;
1682         const struct osd_lf_map    *map;
1683         struct dentry              *child;
1684         int                         rc       = 0;
1685         ENTRY;
1686
1687         /* skip any '.' started names */
1688         if (name[0] == '.')
1689                 RETURN(0);
1690
1691         for (map = osd_dl_maps; map->olm_name != NULL; map++) {
1692                 if (strlen(map->olm_name) != namelen)
1693                         continue;
1694
1695                 if (strncmp(map->olm_name, name, namelen) == 0)
1696                         break;
1697         }
1698
1699         if (map->olm_name == NULL)
1700                 RETURN(0);
1701
1702         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1703         if (IS_ERR(child))
1704                 RETURN(PTR_ERR(child));
1705
1706         rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1707                               &map->olm_fid, map->olm_flags);
1708         dput(child);
1709
1710         RETURN(rc);
1711 }
1712
1713 static int osd_ios_root_fill(void *buf, const char *name, int namelen,
1714                              loff_t offset, __u64 ino, unsigned d_type)
1715 {
1716         struct osd_ios_filldir_buf *fill_buf = buf;
1717         struct osd_device          *dev      = fill_buf->oifb_dev;
1718         const struct osd_lf_map    *map;
1719         struct dentry              *child;
1720         int                         rc       = 0;
1721         ENTRY;
1722
1723         /* skip any '.' started names */
1724         if (name[0] == '.')
1725                 RETURN(0);
1726
1727         for (map = osd_lf_maps; map->olm_name != NULL; map++) {
1728                 if (strlen(map->olm_name) != namelen)
1729                         continue;
1730
1731                 if (strncmp(map->olm_name, name, namelen) == 0)
1732                         break;
1733         }
1734
1735         if (map->olm_name == NULL)
1736                 RETURN(0);
1737
1738         child = osd_ios_lookup_one_len(name, fill_buf->oifb_dentry, namelen);
1739         if (IS_ERR(child))
1740                 RETURN(PTR_ERR(child));
1741
1742         if (!(map->olm_flags & OLF_NO_OI))
1743                 rc = osd_ios_scan_one(fill_buf->oifb_info, dev, child->d_inode,
1744                                       &map->olm_fid, map->olm_flags);
1745         if (rc == 0 && map->olm_flags & OLF_SCAN_SUBITEMS)
1746                 rc = osd_ios_new_item(dev, child, map->olm_scandir,
1747                                       map->olm_filldir);
1748         dput(child);
1749
1750         RETURN(rc);
1751 }
1752
1753 static int
1754 osd_ios_general_scan(struct osd_thread_info *info, struct osd_device *dev,
1755                      struct dentry *dentry, filldir_t filldir)
1756 {
1757         struct osd_ios_filldir_buf    buf   = {
1758 #ifdef HAVE_DIR_CONTEXT
1759                                                 .ctx.actor = filldir,
1760 #endif
1761                                                 .oifb_info = info,
1762                                                 .oifb_dev = dev,
1763                                                 .oifb_dentry = dentry };
1764         struct file                  *filp  = &info->oti_it_ea.oie_file;
1765         struct inode                 *inode = dentry->d_inode;
1766         const struct file_operations *fops  = inode->i_fop;
1767         int                           rc;
1768         ENTRY;
1769
1770         LASSERT(filldir != NULL);
1771
1772         filp->f_pos = 0;
1773         filp->f_dentry = dentry;
1774         filp->f_mode = FMODE_64BITHASH;
1775         filp->f_mapping = inode->i_mapping;
1776         filp->f_op = fops;
1777         filp->private_data = NULL;
1778         set_file_inode(filp, inode);
1779
1780 #ifdef HAVE_DIR_CONTEXT
1781         buf.ctx.pos = filp->f_pos;
1782         rc = fops->iterate(filp, &buf.ctx);
1783         filp->f_pos = buf.ctx.pos;
1784 #else
1785         rc = fops->readdir(filp, &buf, filldir);
1786 #endif
1787         fops->release(inode, filp);
1788
1789         RETURN(rc);
1790 }
1791
1792 static int
1793 osd_ios_ROOT_scan(struct osd_thread_info *info, struct osd_device *dev,
1794                   struct dentry *dentry, filldir_t filldir)
1795 {
1796         struct osd_scrub  *scrub  = &dev->od_scrub;
1797         struct scrub_file *sf     = &scrub->os_file;
1798         struct dentry     *child;
1799         int                rc;
1800         ENTRY;
1801
1802         /* It is existing MDT0 device. We only allow the case of object without
1803          * LMA to happen on the MDT0, which is usually for old 1.8 MDT. Then we
1804          * can generate IGIF mode FID for the object and related OI mapping. If
1805          * it is on other MDTs, then becuase file-level backup/restore, related
1806          * OI mapping may be invalid already, we do not know which is the right
1807          * FID for the object. We only allow IGIF objects to reside on the MDT0.
1808          *
1809          * XXX: For the case of object on non-MDT0 device with neither LMA nor
1810          *      "fid" xattr, then something crashed. We cannot re-generate the
1811          *      FID directly, instead, the OI scrub will scan the OI structure
1812          *      and try to re-generate the LMA from the OI mapping. But if the
1813          *      OI mapping crashed or lost also, then we have to give up under
1814          *      double failure cases. */
1815         scrub->os_convert_igif = 1;
1816         child = osd_ios_lookup_one_len(dot_lustre_name, dentry,
1817                                        strlen(dot_lustre_name));
1818         if (IS_ERR(child)) {
1819                 rc = PTR_ERR(child);
1820                 if (rc == -ENOENT) {
1821                         /* It is 1.8 MDT device. */
1822                         if (!(sf->sf_flags & SF_UPGRADE)) {
1823                                 osd_scrub_file_reset(scrub,
1824                                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid,
1825                                         SF_UPGRADE);
1826                                 sf->sf_internal_flags &= ~SIF_NO_HANDLE_OLD_FID;
1827                                 rc = osd_scrub_file_store(scrub);
1828                         } else {
1829                                 rc = 0;
1830                         }
1831                 }
1832         } else {
1833                 /* For lustre-2.x (x <= 3), the ".lustre" has NO FID-in-LMA,
1834                  * so the client will get IGIF for the ".lustre" object when
1835                  * the MDT restart.
1836                  *
1837                  * From the OI scrub view, when the MDT upgrade to Lustre-2.4,
1838                  * it does not know whether there are some old clients cached
1839                  * the ".lustre" IGIF during the upgrading. Two choices:
1840                  *
1841                  * 1) Generate IGIF-in-LMA and IGIF-in-OI for the ".lustre".
1842                  *    It will allow the old connected clients to access the
1843                  *    ".lustre" with cached IGIF. But it will cause others
1844                  *    on the MDT failed to check "fid_is_dot_lustre()".
1845                  *
1846                  * 2) Use fixed FID {FID_SEQ_DOT_LUSTRE, FID_OID_DOT_LUSTRE, 0}
1847                  *    for ".lustre" in spite of whether there are some clients
1848                  *    cached the ".lustre" IGIF or not. It enables the check
1849                  *    "fid_is_dot_lustre()" on the MDT, although it will cause
1850                  *    that the old connected clients cannot access the ".lustre"
1851                  *    with the cached IGIF.
1852                  *
1853                  * Usually, it is rare case for the old connected clients
1854                  * to access the ".lustre" with cached IGIF. So we prefer
1855                  * to the solution 2). */
1856                 rc = osd_ios_scan_one(info, dev, child->d_inode,
1857                                       &LU_DOT_LUSTRE_FID, 0);
1858                 if (rc == 0)
1859                         rc = osd_ios_new_item(dev, child, osd_ios_general_scan,
1860                                               osd_ios_dl_fill);
1861                 dput(child);
1862         }
1863
1864         RETURN(rc);
1865 }
1866
1867 static int
1868 osd_ios_OBJECTS_scan(struct osd_thread_info *info, struct osd_device *dev,
1869                      struct dentry *dentry, filldir_t filldir)
1870 {
1871         struct osd_scrub  *scrub  = &dev->od_scrub;
1872         struct scrub_file *sf     = &scrub->os_file;
1873         struct dentry     *child;
1874         int                rc;
1875         ENTRY;
1876
1877         if (unlikely(sf->sf_internal_flags & SIF_NO_HANDLE_OLD_FID)) {
1878                 sf->sf_internal_flags &= ~SIF_NO_HANDLE_OLD_FID;
1879                 rc = osd_scrub_file_store(scrub);
1880                 if (rc != 0)
1881                         RETURN(rc);
1882         }
1883
1884         child = osd_ios_lookup_one_len(ADMIN_USR, dentry, strlen(ADMIN_USR));
1885         if (!IS_ERR(child)) {
1886                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1887                 dput(child);
1888         } else {
1889                 rc = PTR_ERR(child);
1890         }
1891
1892         if (rc != 0 && rc != -ENOENT)
1893                 RETURN(rc);
1894
1895         child = osd_ios_lookup_one_len(ADMIN_GRP, dentry, strlen(ADMIN_GRP));
1896         if (!IS_ERR(child)) {
1897                 rc = osd_ios_scan_one(info, dev, child->d_inode, NULL, 0);
1898                 dput(child);
1899         } else {
1900                 rc = PTR_ERR(child);
1901         }
1902
1903         if (rc == -ENOENT)
1904                 rc = 0;
1905
1906         RETURN(rc);
1907 }
1908
1909 static int osd_initial_OI_scrub(struct osd_thread_info *info,
1910                                 struct osd_device *dev)
1911 {
1912         struct osd_ios_item     *item    = NULL;
1913         scandir_t                scandir = osd_ios_general_scan;
1914         filldir_t                filldir = osd_ios_root_fill;
1915         struct dentry           *dentry  = osd_sb(dev)->s_root;
1916         const struct osd_lf_map *map     = osd_lf_maps;
1917         int                      rc;
1918         ENTRY;
1919
1920         /* Lookup IGIF in OI by force for initial OI scrub. */
1921         dev->od_igif_inoi = 1;
1922
1923         while (1) {
1924                 rc = scandir(info, dev, dentry, filldir);
1925                 if (item != NULL) {
1926                         dput(item->oii_dentry);
1927                         OBD_FREE_PTR(item);
1928                 }
1929
1930                 if (rc != 0)
1931                         break;
1932
1933                 if (list_empty(&dev->od_ios_list))
1934                         break;
1935
1936                 item = list_entry(dev->od_ios_list.next,
1937                                   struct osd_ios_item, oii_list);
1938                 list_del_init(&item->oii_list);
1939
1940                 LASSERT(item->oii_scandir != NULL);
1941                 scandir = item->oii_scandir;
1942                 filldir = item->oii_filldir;
1943                 dentry = item->oii_dentry;
1944         }
1945
1946         while (!list_empty(&dev->od_ios_list)) {
1947                 item = list_entry(dev->od_ios_list.next,
1948                                   struct osd_ios_item, oii_list);
1949                 list_del_init(&item->oii_list);
1950                 dput(item->oii_dentry);
1951                 OBD_FREE_PTR(item);
1952         }
1953
1954         if (rc != 0)
1955                 RETURN(rc);
1956
1957         /* There maybe the case that the object has been removed, but its OI
1958          * mapping is still in the OI file, such as the "CATALOGS" after MDT
1959          * file-level backup/restore. So here cleanup the stale OI mappings. */
1960         while (map->olm_name != NULL) {
1961                 struct dentry *child;
1962
1963                 if (fid_is_zero(&map->olm_fid)) {
1964                         map++;
1965                         continue;
1966                 }
1967
1968                 child = osd_ios_lookup_one_len(map->olm_name,
1969                                                osd_sb(dev)->s_root,
1970                                                strlen(map->olm_name));
1971                 if (!IS_ERR(child))
1972                         dput(child);
1973                 else if (PTR_ERR(child) == -ENOENT)
1974                         osd_scrub_refresh_mapping(info, dev, &map->olm_fid,
1975                                                   NULL, DTO_INDEX_DELETE,
1976                                                   true, 0);
1977                 map++;
1978         }
1979
1980         RETURN(0);
1981 }
1982
1983 char *osd_lf_fid2name(const struct lu_fid *fid)
1984 {
1985         const struct osd_lf_map *map = osd_lf_maps;
1986
1987         while (map->olm_name != NULL) {
1988                 if (!lu_fid_eq(fid, &map->olm_fid)) {
1989                         map++;
1990                         continue;
1991                 }
1992
1993                 if (map->olm_flags & OLF_SHOW_NAME)
1994                         return map->olm_name;
1995                 else
1996                         return "";
1997         }
1998
1999         return NULL;
2000 }
2001
2002 /* OI scrub start/stop */
2003
2004 static int do_osd_scrub_start(struct osd_device *dev, __u32 flags)
2005 {
2006         struct osd_scrub     *scrub  = &dev->od_scrub;
2007         struct ptlrpc_thread *thread = &scrub->os_thread;
2008         struct l_wait_info    lwi    = { 0 };
2009         struct task_struct   *task;
2010         int                   rc;
2011         ENTRY;
2012
2013 again:
2014         /* os_lock: sync status between stop and scrub thread */
2015         spin_lock(&scrub->os_lock);
2016         if (thread_is_running(thread)) {
2017                 spin_unlock(&scrub->os_lock);
2018                 RETURN(-EALREADY);
2019         } else if (unlikely(thread_is_stopping(thread))) {
2020                 spin_unlock(&scrub->os_lock);
2021                 l_wait_event(thread->t_ctl_waitq,
2022                              thread_is_stopped(thread),
2023                              &lwi);
2024                 goto again;
2025         }
2026         spin_unlock(&scrub->os_lock);
2027
2028         if (scrub->os_file.sf_status == SS_COMPLETED) {
2029                 if (!(flags & SS_SET_FAILOUT))
2030                         flags |= SS_CLEAR_FAILOUT;
2031
2032                 if (!(flags & SS_SET_DRYRUN))
2033                         flags |= SS_CLEAR_DRYRUN;
2034
2035                 flags |= SS_RESET;
2036         }
2037
2038         scrub->os_start_flags = flags;
2039         thread_set_flags(thread, 0);
2040         task = kthread_run(osd_scrub_main, dev, "OI_scrub");
2041         if (IS_ERR(task)) {
2042                 rc = PTR_ERR(task);
2043                 CERROR("%.16s: cannot start iteration thread: rc = %d\n",
2044                        osd_scrub2name(scrub), rc);
2045                 RETURN(rc);
2046         }
2047
2048         l_wait_event(thread->t_ctl_waitq,
2049                      thread_is_running(thread) || thread_is_stopped(thread),
2050                      &lwi);
2051
2052         RETURN(0);
2053 }
2054
2055 int osd_scrub_start(struct osd_device *dev)
2056 {
2057         int rc;
2058         ENTRY;
2059
2060         /* od_otable_mutex: prevent curcurrent start/stop */
2061         mutex_lock(&dev->od_otable_mutex);
2062         rc = do_osd_scrub_start(dev, SS_AUTO);
2063         mutex_unlock(&dev->od_otable_mutex);
2064
2065         RETURN(rc == -EALREADY ? 0 : rc);
2066 }
2067
2068 static void do_osd_scrub_stop(struct osd_scrub *scrub)
2069 {
2070         struct ptlrpc_thread *thread = &scrub->os_thread;
2071         struct l_wait_info    lwi    = { 0 };
2072
2073         /* os_lock: sync status between stop and scrub thread */
2074         spin_lock(&scrub->os_lock);
2075         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
2076                 thread_set_flags(thread, SVC_STOPPING);
2077                 spin_unlock(&scrub->os_lock);
2078                 wake_up_all(&thread->t_ctl_waitq);
2079                 l_wait_event(thread->t_ctl_waitq,
2080                              thread_is_stopped(thread),
2081                              &lwi);
2082                 /* Do not skip the last lock/unlock, which can guarantee that
2083                  * the caller cannot return until the OI scrub thread exit. */
2084                 spin_lock(&scrub->os_lock);
2085         }
2086         spin_unlock(&scrub->os_lock);
2087 }
2088
2089 static void osd_scrub_stop(struct osd_device *dev)
2090 {
2091         /* od_otable_mutex: prevent curcurrent start/stop */
2092         mutex_lock(&dev->od_otable_mutex);
2093         dev->od_scrub.os_paused = 1;
2094         do_osd_scrub_stop(&dev->od_scrub);
2095         mutex_unlock(&dev->od_otable_mutex);
2096 }
2097
2098 /* OI scrub setup/cleanup */
2099
2100 static const char osd_scrub_name[] = "OI_scrub";
2101
2102 int osd_scrub_setup(const struct lu_env *env, struct osd_device *dev)
2103 {
2104         struct osd_thread_info     *info   = osd_oti_get(env);
2105         struct osd_scrub           *scrub  = &dev->od_scrub;
2106         struct lvfs_run_ctxt       *ctxt   = &scrub->os_ctxt;
2107         struct scrub_file          *sf     = &scrub->os_file;
2108         struct super_block         *sb     = osd_sb(dev);
2109         struct ldiskfs_super_block *es     = LDISKFS_SB(sb)->s_es;
2110         struct lvfs_run_ctxt        saved;
2111         struct file                *filp;
2112         struct inode               *inode;
2113         struct lu_fid              *fid    = &info->oti_fid;
2114         int                         dirty  = 0;
2115         int                         rc     = 0;
2116         ENTRY;
2117
2118         memset(scrub, 0, sizeof(*scrub));
2119         OBD_SET_CTXT_MAGIC(ctxt);
2120         ctxt->pwdmnt = dev->od_mnt;
2121         ctxt->pwd = dev->od_mnt->mnt_root;
2122         ctxt->fs = get_ds();
2123
2124         init_waitqueue_head(&scrub->os_thread.t_ctl_waitq);
2125         init_rwsem(&scrub->os_rwsem);
2126         spin_lock_init(&scrub->os_lock);
2127         INIT_LIST_HEAD(&scrub->os_inconsistent_items);
2128
2129         push_ctxt(&saved, ctxt);
2130         filp = filp_open(osd_scrub_name, O_RDWR | O_CREAT, 0644);
2131         if (IS_ERR(filp)) {
2132                 pop_ctxt(&saved, ctxt);
2133                 RETURN(PTR_ERR(filp));
2134         }
2135
2136         inode = filp->f_dentry->d_inode;
2137         /* 'What the @fid is' is not imporatant, because the object
2138          * has no OI mapping, and only is visible inside the OSD.*/
2139         lu_igif_build(fid, inode->i_ino, inode->i_generation);
2140         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
2141         if (rc != 0) {
2142                 filp_close(filp, 0);
2143                 pop_ctxt(&saved, ctxt);
2144                 RETURN(rc);
2145         }
2146
2147         scrub->os_inode = igrab(inode);
2148         filp_close(filp, 0);
2149         pop_ctxt(&saved, ctxt);
2150
2151         rc = osd_scrub_file_load(scrub);
2152         if (rc == -ENOENT) {
2153                 osd_scrub_file_init(scrub, es->s_uuid);
2154                 /* If the "/O" dir does not exist when mount (indicated by
2155                  * osd_device::od_maybe_new), neither for the "/OI_scrub",
2156                  * then it is quite probably that the device is a new one,
2157                  * under such case, mark it as SIF_NO_HANDLE_OLD_FID.
2158                  *
2159                  * For the rare case that "/O" and "OI_scrub" both lost on
2160                  * an old device, it can be found and cleared later.
2161                  *
2162                  * For the system with "SIF_NO_HANDLE_OLD_FID", we do not
2163                  * need to check "filter_fid_old" and to convert it to
2164                  * "filter_fid" for each object, and all the IGIF should
2165                  * have their FID mapping in OI files already. */
2166                 if (dev->od_maybe_new)
2167                         sf->sf_internal_flags = SIF_NO_HANDLE_OLD_FID;
2168                 dirty = 1;
2169         } else if (rc != 0) {
2170                 RETURN(rc);
2171         } else {
2172                 if (memcmp(sf->sf_uuid, es->s_uuid, 16) != 0) {
2173                         osd_scrub_file_reset(scrub, es->s_uuid,SF_INCONSISTENT);
2174                         dirty = 1;
2175                 } else if (sf->sf_status == SS_SCANNING) {
2176                         sf->sf_status = SS_CRASHED;
2177                         dirty = 1;
2178                 }
2179         }
2180
2181         if (sf->sf_pos_last_checkpoint != 0)
2182                 scrub->os_pos_current = sf->sf_pos_last_checkpoint + 1;
2183         else
2184                 scrub->os_pos_current = LDISKFS_FIRST_INO(sb) + 1;
2185
2186         if (dirty != 0) {
2187                 rc = osd_scrub_file_store(scrub);
2188                 if (rc != 0)
2189                         RETURN(rc);
2190         }
2191
2192         /* Initialize OI files. */
2193         rc = osd_oi_init(info, dev);
2194         if (rc < 0)
2195                 RETURN(rc);
2196
2197         rc = osd_initial_OI_scrub(info, dev);
2198         if (rc == 0) {
2199                 if (sf->sf_flags & SF_UPGRADE ||
2200                     !(sf->sf_internal_flags & SIF_NO_HANDLE_OLD_FID ||
2201                       sf->sf_success_count > 0)) {
2202                         dev->od_igif_inoi = 0;
2203                         dev->od_check_ff = dev->od_is_ost;
2204                 } else {
2205                         dev->od_igif_inoi = 1;
2206                         dev->od_check_ff = 0;
2207                 }
2208
2209                 if (sf->sf_flags & SF_INCONSISTENT)
2210                         /* The 'od_igif_inoi' will be set under the
2211                          * following cases:
2212                          * 1) new created system, or
2213                          * 2) restored from file-level backup, or
2214                          * 3) the upgrading completed.
2215                          *
2216                          * The 'od_igif_inoi' may be cleared by OI scrub
2217                          * later if found that the system is upgrading. */
2218                         dev->od_igif_inoi = 1;
2219
2220                 if (!dev->od_noscrub &&
2221                     ((sf->sf_status == SS_PAUSED) ||
2222                      (sf->sf_status == SS_CRASHED &&
2223                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
2224                                       SF_UPGRADE | SF_AUTO)) ||
2225                      (sf->sf_status == SS_INIT &&
2226                       sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT |
2227                                       SF_UPGRADE))))
2228                         rc = osd_scrub_start(dev);
2229         }
2230
2231         /* it is possible that dcache entries may keep objects after they are
2232          * deleted by OSD. While it looks safe this can cause object data to
2233          * stay until umount causing failures in tests calculating free space,
2234          * e.g. replay-ost-single. Since those dcache entries are not used
2235          * anymore let's just free them after use here */
2236         shrink_dcache_sb(sb);
2237
2238         RETURN(rc);
2239 }
2240
2241 void osd_scrub_cleanup(const struct lu_env *env, struct osd_device *dev)
2242 {
2243         struct osd_scrub *scrub = &dev->od_scrub;
2244
2245         LASSERT(dev->od_otable_it == NULL);
2246
2247         if (scrub->os_inode != NULL) {
2248                 osd_scrub_stop(dev);
2249                 iput(scrub->os_inode);
2250                 scrub->os_inode = NULL;
2251         }
2252         if (dev->od_oi_table != NULL)
2253                 osd_oi_fini(osd_oti_get(env), dev);
2254 }
2255
2256 /* object table based iteration APIs */
2257
2258 static struct dt_it *osd_otable_it_init(const struct lu_env *env,
2259                                        struct dt_object *dt, __u32 attr,
2260                                        struct lustre_capa *capa)
2261 {
2262         enum dt_otable_it_flags flags = attr >> DT_OTABLE_IT_FLAGS_SHIFT;
2263         enum dt_otable_it_valid valid = attr & ~DT_OTABLE_IT_FLAGS_MASK;
2264         struct osd_device      *dev   = osd_dev(dt->do_lu.lo_dev);
2265         struct osd_scrub       *scrub = &dev->od_scrub;
2266         struct osd_otable_it   *it;
2267         __u32                   start = 0;
2268         int                     rc;
2269         ENTRY;
2270
2271         /* od_otable_mutex: prevent curcurrent init/fini */
2272         mutex_lock(&dev->od_otable_mutex);
2273         if (dev->od_otable_it != NULL)
2274                 GOTO(out, it = ERR_PTR(-EALREADY));
2275
2276         OBD_ALLOC_PTR(it);
2277         if (it == NULL)
2278                 GOTO(out, it = ERR_PTR(-ENOMEM));
2279
2280         dev->od_otable_it = it;
2281         it->ooi_dev = dev;
2282         it->ooi_cache.ooc_consumer_idx = -1;
2283         if (flags & DOIF_OUTUSED)
2284                 it->ooi_used_outside = 1;
2285
2286         if (flags & DOIF_RESET)
2287                 start |= SS_RESET;
2288
2289         if (valid & DOIV_ERROR_HANDLE) {
2290                 if (flags & DOIF_FAILOUT)
2291                         start |= SS_SET_FAILOUT;
2292                 else
2293                         start |= SS_CLEAR_FAILOUT;
2294         }
2295
2296         if (valid & DOIV_DRYRUN) {
2297                 if (flags & DOIF_DRYRUN)
2298                         start |= SS_SET_DRYRUN;
2299                 else
2300                         start |= SS_CLEAR_DRYRUN;
2301         }
2302
2303         rc = do_osd_scrub_start(dev, start);
2304         if (rc < 0 && rc != -EALREADY) {
2305                 dev->od_otable_it = NULL;
2306                 OBD_FREE_PTR(it);
2307                 GOTO(out, it = ERR_PTR(rc));
2308         }
2309
2310         it->ooi_cache.ooc_pos_preload = scrub->os_pos_current;
2311
2312         GOTO(out, it);
2313
2314 out:
2315         mutex_unlock(&dev->od_otable_mutex);
2316         return (struct dt_it *)it;
2317 }
2318
2319 static void osd_otable_it_fini(const struct lu_env *env, struct dt_it *di)
2320 {
2321         struct osd_otable_it *it  = (struct osd_otable_it *)di;
2322         struct osd_device    *dev = it->ooi_dev;
2323
2324         /* od_otable_mutex: prevent curcurrent init/fini */
2325         mutex_lock(&dev->od_otable_mutex);
2326         do_osd_scrub_stop(&dev->od_scrub);
2327         LASSERT(dev->od_otable_it == it);
2328
2329         dev->od_otable_it = NULL;
2330         mutex_unlock(&dev->od_otable_mutex);
2331         OBD_FREE_PTR(it);
2332 }
2333
2334 static int osd_otable_it_get(const struct lu_env *env,
2335                              struct dt_it *di, const struct dt_key *key)
2336 {
2337         return 0;
2338 }
2339
2340 static void osd_otable_it_put(const struct lu_env *env, struct dt_it *di)
2341 {
2342 }
2343
2344 static inline int
2345 osd_otable_it_wakeup(struct osd_scrub *scrub, struct osd_otable_it *it)
2346 {
2347         spin_lock(&scrub->os_lock);
2348         if (it->ooi_cache.ooc_pos_preload < scrub->os_pos_current ||
2349             scrub->os_waiting ||
2350             !thread_is_running(&scrub->os_thread))
2351                 it->ooi_waiting = 0;
2352         else
2353                 it->ooi_waiting = 1;
2354         spin_unlock(&scrub->os_lock);
2355
2356         return !it->ooi_waiting;
2357 }
2358
2359 static int osd_otable_it_next(const struct lu_env *env, struct dt_it *di)
2360 {
2361         struct osd_otable_it    *it     = (struct osd_otable_it *)di;
2362         struct osd_device       *dev    = it->ooi_dev;
2363         struct osd_scrub        *scrub  = &dev->od_scrub;
2364         struct osd_otable_cache *ooc    = &it->ooi_cache;
2365         struct ptlrpc_thread    *thread = &scrub->os_thread;
2366         struct l_wait_info       lwi    = { 0 };
2367         int                      rc;
2368         ENTRY;
2369
2370         LASSERT(it->ooi_user_ready);
2371
2372 again:
2373         if (!thread_is_running(thread) && !it->ooi_used_outside)
2374                 RETURN(1);
2375
2376         if (ooc->ooc_cached_items > 0) {
2377                 ooc->ooc_cached_items--;
2378                 ooc->ooc_consumer_idx = (ooc->ooc_consumer_idx + 1) &
2379                                         ~OSD_OTABLE_IT_CACHE_MASK;
2380                 RETURN(0);
2381         }
2382
2383         if (it->ooi_all_cached) {
2384                 l_wait_event(thread->t_ctl_waitq,
2385                              !thread_is_running(thread),
2386                              &lwi);
2387                 RETURN(1);
2388         }
2389
2390         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
2391                 spin_lock(&scrub->os_lock);
2392                 scrub->os_waiting = 0;
2393                 wake_up_all(&scrub->os_thread.t_ctl_waitq);
2394                 spin_unlock(&scrub->os_lock);
2395         }
2396
2397         if (it->ooi_cache.ooc_pos_preload >= scrub->os_pos_current)
2398                 l_wait_event(thread->t_ctl_waitq,
2399                              osd_otable_it_wakeup(scrub, it),
2400                              &lwi);
2401
2402         if (!thread_is_running(thread) && !it->ooi_used_outside)
2403                 RETURN(1);
2404
2405         rc = osd_otable_it_preload(env, it);
2406         if (rc >= 0)
2407                 goto again;
2408
2409         RETURN(rc);
2410 }
2411
2412 static struct dt_key *osd_otable_it_key(const struct lu_env *env,
2413                                         const struct dt_it *di)
2414 {
2415         return NULL;
2416 }
2417
2418 static int osd_otable_it_key_size(const struct lu_env *env,
2419                                   const struct dt_it *di)
2420 {
2421         return sizeof(__u64);
2422 }
2423
2424 static int osd_otable_it_rec(const struct lu_env *env, const struct dt_it *di,
2425                              struct dt_rec *rec, __u32 attr)
2426 {
2427         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
2428         struct osd_otable_cache *ooc = &it->ooi_cache;
2429
2430         *(struct lu_fid *)rec = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_fid;
2431
2432         /* Filter out Invald FID already. */
2433         LASSERTF(fid_is_sane((struct lu_fid *)rec),
2434                  "Invalid FID "DFID", p_idx = %d, c_idx = %d\n",
2435                  PFID((struct lu_fid *)rec),
2436                  ooc->ooc_producer_idx, ooc->ooc_consumer_idx);
2437
2438         return 0;
2439 }
2440
2441 static __u64 osd_otable_it_store(const struct lu_env *env,
2442                                  const struct dt_it *di)
2443 {
2444         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
2445         struct osd_otable_cache *ooc = &it->ooi_cache;
2446         __u64                    hash;
2447
2448         if (it->ooi_user_ready && ooc->ooc_consumer_idx != -1)
2449                 hash = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_lid.oii_ino;
2450         else
2451                 hash = ooc->ooc_pos_preload;
2452         return hash;
2453 }
2454
2455 /**
2456  * Set the OSD layer iteration start position as the specified hash.
2457  */
2458 static int osd_otable_it_load(const struct lu_env *env,
2459                               const struct dt_it *di, __u64 hash)
2460 {
2461         struct osd_otable_it    *it    = (struct osd_otable_it *)di;
2462         struct osd_device       *dev   = it->ooi_dev;
2463         struct osd_otable_cache *ooc   = &it->ooi_cache;
2464         struct osd_scrub        *scrub = &dev->od_scrub;
2465         int                      rc;
2466         ENTRY;
2467
2468         /* Forbid to set iteration position after iteration started. */
2469         if (it->ooi_user_ready)
2470                 RETURN(-EPERM);
2471
2472         if (hash > OSD_OTABLE_MAX_HASH)
2473                 hash = OSD_OTABLE_MAX_HASH;
2474
2475         ooc->ooc_pos_preload = hash;
2476         if (ooc->ooc_pos_preload <= LDISKFS_FIRST_INO(osd_sb(dev)))
2477                 ooc->ooc_pos_preload = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
2478
2479         it->ooi_user_ready = 1;
2480         if (!scrub->os_full_speed)
2481                 wake_up_all(&scrub->os_thread.t_ctl_waitq);
2482
2483         /* Unplug OSD layer iteration by the first next() call. */
2484         rc = osd_otable_it_next(env, (struct dt_it *)it);
2485
2486         RETURN(rc);
2487 }
2488
2489 static int osd_otable_it_key_rec(const struct lu_env *env,
2490                                  const struct dt_it *di, void *key_rec)
2491 {
2492         return 0;
2493 }
2494
2495 const struct dt_index_operations osd_otable_ops = {
2496         .dio_it = {
2497                 .init     = osd_otable_it_init,
2498                 .fini     = osd_otable_it_fini,
2499                 .get      = osd_otable_it_get,
2500                 .put      = osd_otable_it_put,
2501                 .next     = osd_otable_it_next,
2502                 .key      = osd_otable_it_key,
2503                 .key_size = osd_otable_it_key_size,
2504                 .rec      = osd_otable_it_rec,
2505                 .store    = osd_otable_it_store,
2506                 .load     = osd_otable_it_load,
2507                 .key_rec  = osd_otable_it_key_rec,
2508         }
2509 };
2510
2511 /* high priority inconsistent items list APIs */
2512
2513 int osd_oii_insert(struct osd_device *dev, struct osd_idmap_cache *oic,
2514                    int insert)
2515 {
2516         struct osd_inconsistent_item *oii;
2517         struct osd_scrub             *scrub  = &dev->od_scrub;
2518         struct ptlrpc_thread         *thread = &scrub->os_thread;
2519         int                           wakeup = 0;
2520         ENTRY;
2521
2522         OBD_ALLOC_PTR(oii);
2523         if (unlikely(oii == NULL))
2524                 RETURN(-ENOMEM);
2525
2526         INIT_LIST_HEAD(&oii->oii_list);
2527         oii->oii_cache = *oic;
2528         oii->oii_insert = insert;
2529
2530         spin_lock(&scrub->os_lock);
2531         if (unlikely(!thread_is_running(thread))) {
2532                 spin_unlock(&scrub->os_lock);
2533                 OBD_FREE_PTR(oii);
2534                 RETURN(-EAGAIN);
2535         }
2536
2537         if (list_empty(&scrub->os_inconsistent_items))
2538                 wakeup = 1;
2539         list_add_tail(&oii->oii_list, &scrub->os_inconsistent_items);
2540         spin_unlock(&scrub->os_lock);
2541
2542         if (wakeup != 0)
2543                 wake_up_all(&thread->t_ctl_waitq);
2544
2545         RETURN(0);
2546 }
2547
2548 int osd_oii_lookup(struct osd_device *dev, const struct lu_fid *fid,
2549                    struct osd_inode_id *id)
2550 {
2551         struct osd_scrub             *scrub = &dev->od_scrub;
2552         struct osd_inconsistent_item *oii;
2553         ENTRY;
2554
2555         spin_lock(&scrub->os_lock);
2556         list_for_each_entry(oii, &scrub->os_inconsistent_items, oii_list) {
2557                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
2558                         *id = oii->oii_cache.oic_lid;
2559                         spin_unlock(&scrub->os_lock);
2560                         RETURN(0);
2561                 }
2562         }
2563         spin_unlock(&scrub->os_lock);
2564
2565         RETURN(-ENOENT);
2566 }
2567
2568 /* OI scrub dump */
2569
2570 static const char *scrub_status_names[] = {
2571         "init",
2572         "scanning",
2573         "completed",
2574         "failed",
2575         "stopped",
2576         "paused",
2577         "crashed",
2578         NULL
2579 };
2580
2581 static const char *scrub_flags_names[] = {
2582         "recreated",
2583         "inconsistent",
2584         "auto",
2585         "upgrade",
2586         NULL
2587 };
2588
2589 static const char *scrub_param_names[] = {
2590         "failout",
2591         "dryrun",
2592         NULL
2593 };
2594
2595 static int scrub_bits_dump(struct seq_file *m, int bits, const char *names[],
2596                            const char *prefix)
2597 {
2598         int flag;
2599         int rc;
2600         int i;
2601
2602         rc = seq_printf(m, "%s:%c", prefix, bits != 0 ? ' ' : '\n');
2603         if (rc < 0)
2604                 return rc;
2605
2606         for (i = 0, flag = 1; bits != 0; i++, flag = 1 << i) {
2607                 if (flag & bits) {
2608                         bits &= ~flag;
2609                         rc = seq_printf(m, "%s%c", names[i],
2610                                         bits != 0 ? ',' : '\n');
2611                         if (rc < 0)
2612                                 return rc;
2613                 }
2614         }
2615         return 0;
2616 }
2617
2618 static int scrub_time_dump(struct seq_file *m, __u64 time, const char *prefix)
2619 {
2620         int rc;
2621
2622         if (time != 0)
2623                 rc = seq_printf(m, "%s: "LPU64" seconds\n", prefix,
2624                               cfs_time_current_sec() - time);
2625         else
2626                 rc = seq_printf(m, "%s: N/A\n", prefix);
2627         return rc;
2628 }
2629
2630 static int scrub_pos_dump(struct seq_file *m, __u64 pos, const char *prefix)
2631 {
2632         int rc;
2633
2634         if (pos != 0)
2635                 rc = seq_printf(m, "%s: "LPU64"\n", prefix, pos);
2636         else
2637                 rc = seq_printf(m, "%s: N/A\n", prefix);
2638         return rc;
2639 }
2640
2641 int osd_scrub_dump(struct seq_file *m, struct osd_device *dev)
2642 {
2643         struct osd_scrub  *scrub   = &dev->od_scrub;
2644         struct scrub_file *sf      = &scrub->os_file;
2645         __u64              checked;
2646         __u64              speed;
2647         int                rc;
2648
2649         down_read(&scrub->os_rwsem);
2650         rc = seq_printf(m, "name: OI_scrub\n"
2651                         "magic: 0x%x\n"
2652                         "oi_files: %d\n"
2653                         "status: %s\n",
2654                         sf->sf_magic, (int)sf->sf_oi_count,
2655                         scrub_status_names[sf->sf_status]);
2656         if (rc < 0)
2657                 goto out;
2658
2659         rc = scrub_bits_dump(m, sf->sf_flags, scrub_flags_names,
2660                              "flags");
2661         if (rc < 0)
2662                 goto out;
2663
2664         rc = scrub_bits_dump(m, sf->sf_param, scrub_param_names,
2665                              "param");
2666         if (rc < 0)
2667                 goto out;
2668
2669         rc = scrub_time_dump(m, sf->sf_time_last_complete,
2670                              "time_since_last_completed");
2671         if (rc < 0)
2672                 goto out;
2673
2674         rc = scrub_time_dump(m, sf->sf_time_latest_start,
2675                              "time_since_latest_start");
2676         if (rc < 0)
2677                 goto out;
2678
2679         rc = scrub_time_dump(m, sf->sf_time_last_checkpoint,
2680                              "time_since_last_checkpoint");
2681         if (rc < 0)
2682                 goto out;
2683
2684         rc = scrub_pos_dump(m, sf->sf_pos_latest_start,
2685                             "latest_start_position");
2686         if (rc < 0)
2687                 goto out;
2688
2689         rc = scrub_pos_dump(m, sf->sf_pos_last_checkpoint,
2690                             "last_checkpoint_position");
2691         if (rc < 0)
2692                 goto out;
2693
2694         rc = scrub_pos_dump(m, sf->sf_pos_first_inconsistent,
2695                             "first_failure_position");
2696         if (rc < 0)
2697                 goto out;
2698
2699         checked = sf->sf_items_checked + scrub->os_new_checked;
2700         rc = seq_printf(m, "checked: "LPU64"\n"
2701                       "updated: "LPU64"\n"
2702                       "failed: "LPU64"\n"
2703                       "prior_updated: "LPU64"\n"
2704                       "noscrub: "LPU64"\n"
2705                       "igif: "LPU64"\n"
2706                       "success_count: %u\n",
2707                       checked, sf->sf_items_updated, sf->sf_items_failed,
2708                       sf->sf_items_updated_prior, sf->sf_items_noscrub,
2709                       sf->sf_items_igif, sf->sf_success_count);
2710         if (rc < 0)
2711                 goto out;
2712
2713         speed = checked;
2714         if (thread_is_running(&scrub->os_thread)) {
2715                 cfs_duration_t duration = cfs_time_current() -
2716                                           scrub->os_time_last_checkpoint;
2717                 __u64 new_checked = scrub->os_new_checked * HZ;
2718                 __u32 rtime = sf->sf_run_time +
2719                               cfs_duration_sec(duration + HALF_SEC);
2720
2721                 if (duration != 0)
2722                         do_div(new_checked, duration);
2723                 if (rtime != 0)
2724                         do_div(speed, rtime);
2725                 rc = seq_printf(m, "run_time: %u seconds\n"
2726                               "average_speed: "LPU64" objects/sec\n"
2727                               "real-time_speed: "LPU64" objects/sec\n"
2728                               "current_position: %u\n"
2729                               "lf_scanned: "LPU64"\n"
2730                               "lf_reparied: "LPU64"\n"
2731                               "lf_failed: "LPU64"\n",
2732                               rtime, speed, new_checked, scrub->os_pos_current,
2733                               scrub->os_lf_scanned, scrub->os_lf_repaired,
2734                               scrub->os_lf_failed);
2735         } else {
2736                 if (sf->sf_run_time != 0)
2737                         do_div(speed, sf->sf_run_time);
2738                 rc = seq_printf(m, "run_time: %u seconds\n"
2739                               "average_speed: "LPU64" objects/sec\n"
2740                               "real-time_speed: N/A\n"
2741                               "current_position: N/A\n"
2742                               "lf_scanned: "LPU64"\n"
2743                               "lf_reparied: "LPU64"\n"
2744                               "lf_failed: "LPU64"\n",
2745                               sf->sf_run_time, speed, scrub->os_lf_scanned,
2746                               scrub->os_lf_repaired, scrub->os_lf_failed);
2747         }
2748
2749 out:
2750         up_read(&scrub->os_rwsem);
2751         return (rc < 0 ? -ENOSPC : 0);
2752 }