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