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