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