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