Whamcloud - gitweb
LU-1866 osd: ancillary work for initial OI scrub
[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, 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 #ifndef EXPORT_SYMTAB
39 # define EXPORT_SYMTAB
40 #endif
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <lustre/lustre_idl.h>
44 #include <lustre_disk.h>
45 #include <dt_object.h>
46
47 #include "osd_internal.h"
48 #include "osd_oi.h"
49 #include "osd_scrub.h"
50
51 #define HALF_SEC        (CFS_HZ >> 1)
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
62 /* misc functions */
63
64 static inline struct osd_device *osd_scrub2dev(struct osd_scrub *scrub)
65 {
66         return container_of0(scrub, struct osd_device, od_scrub);
67 }
68
69 static inline struct super_block *osd_scrub2sb(struct osd_scrub *scrub)
70 {
71         return osd_sb(osd_scrub2dev(scrub));
72 }
73
74 static inline int osd_scrub_has_window(struct osd_scrub *scrub,
75                                        struct osd_otable_cache *ooc)
76 {
77         return scrub->os_pos_current < ooc->ooc_pos_preload + SCRUB_WINDOW_SIZE;
78 }
79
80 static int osd_scrub_refresh_mapping(struct osd_thread_info *info,
81                                      struct osd_device *dev,
82                                      const struct lu_fid *fid,
83                                      const struct osd_inode_id *id, int ops)
84 {
85         struct lu_fid         *oi_fid = &info->oti_fid2;
86         struct osd_inode_id   *oi_id  = &info->oti_id2;
87         struct iam_container  *bag;
88         struct iam_path_descr *ipd;
89         handle_t              *jh;
90         int                    rc;
91         ENTRY;
92
93         fid_cpu_to_be(oi_fid, fid);
94         osd_id_pack(oi_id, id);
95         jh = ldiskfs_journal_start_sb(osd_sb(dev),
96                                       osd_dto_credits_noquota[ops]);
97         if (IS_ERR(jh)) {
98                 rc = PTR_ERR(jh);
99                 CERROR("%.16s: fail to start trans for scrub store: rc = %d\n",
100                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
101                 RETURN(rc);
102         }
103
104         bag = &osd_fid2oi(dev, fid)->oi_dir.od_container;
105         ipd = osd_idx_ipd_get(info->oti_env, bag);
106         if (unlikely(ipd == NULL)) {
107                 ldiskfs_journal_stop(jh);
108                 CERROR("%.16s: fail to get ipd for scrub store\n",
109                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name);
110                 RETURN(-ENOMEM);
111         }
112
113         if (ops == DTO_INDEX_UPDATE) {
114                 rc = iam_update(jh, bag, (const struct iam_key *)oi_fid,
115                                 (struct iam_rec *)oi_id, ipd);
116         } else {
117                 rc = iam_insert(jh, bag, (const struct iam_key *)oi_fid,
118                                 (struct iam_rec *)oi_id, ipd);
119                 if (rc == -EEXIST) {
120                         rc = 1;
121                         /* XXX: There are trouble things when adding OI
122                          *      mapping for IGIF object, which may cause
123                          *      multiple objects to be mapped to the same
124                          *      IGIF formatted FID. Consider the following
125                          *      situations:
126                          *
127                          *      1) The MDT is upgrading from 1.8 device.
128                          *      The OI scrub generates IGIF FID1 for the
129                          *      OBJ1 and adds the OI mapping.
130                          *
131                          *      2) For some reason, the OI scrub does not
132                          *      process all the IGIF objects completely.
133                          *
134                          *      3) The MDT is backuped and restored against
135                          *      this device.
136                          *
137                          *      4) When the MDT mounts up, the OI scrub will
138                          *      try to rebuild the OI files. For some IGIF
139                          *      object, OBJ2, which was not processed by the
140                          *      OI scrub before the backup/restore, and the
141                          *      new generated IGIF formatted FID may be just
142                          *      the FID1, the same as OBJ1.
143                          *
144                          *      Under such case, the OI scrub cannot know how
145                          *      to generate new FID for the OBJ2.
146                          *
147                          *      Currently, we do nothing for that. One possible
148                          *      solution is to generate new normal FID for the
149                          *      conflict object.
150                          *
151                          *      Anyway, it is rare, only exists in theory. */
152                 }
153         }
154         osd_ipd_put(info->oti_env, bag, ipd);
155         ldiskfs_journal_stop(jh);
156         RETURN(rc);
157 }
158
159 /* OI_scrub file ops */
160
161 static void osd_scrub_file_to_cpu(struct scrub_file *des,
162                                   struct scrub_file *src)
163 {
164         memcpy(des->sf_uuid, src->sf_uuid, 16);
165         des->sf_flags   = le64_to_cpu(src->sf_flags);
166         des->sf_magic   = le32_to_cpu(src->sf_magic);
167         des->sf_status  = le16_to_cpu(src->sf_status);
168         des->sf_param   = le16_to_cpu(src->sf_param);
169         des->sf_time_last_complete      =
170                                 le64_to_cpu(src->sf_time_last_complete);
171         des->sf_time_latest_start       =
172                                 le64_to_cpu(src->sf_time_latest_start);
173         des->sf_time_last_checkpoint    =
174                                 le64_to_cpu(src->sf_time_last_checkpoint);
175         des->sf_pos_latest_start        =
176                                 le64_to_cpu(src->sf_pos_latest_start);
177         des->sf_pos_last_checkpoint     =
178                                 le64_to_cpu(src->sf_pos_last_checkpoint);
179         des->sf_pos_first_inconsistent  =
180                                 le64_to_cpu(src->sf_pos_first_inconsistent);
181         des->sf_items_checked           =
182                                 le64_to_cpu(src->sf_items_checked);
183         des->sf_items_updated           =
184                                 le64_to_cpu(src->sf_items_updated);
185         des->sf_items_failed            =
186                                 le64_to_cpu(src->sf_items_failed);
187         des->sf_items_updated_prior     =
188                                 le64_to_cpu(src->sf_items_updated_prior);
189         des->sf_run_time        = le32_to_cpu(src->sf_run_time);
190         des->sf_success_count   = le32_to_cpu(src->sf_success_count);
191         des->sf_oi_count        = le16_to_cpu(src->sf_oi_count);
192         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
193 }
194
195 static void osd_scrub_file_to_le(struct scrub_file *des,
196                                  struct scrub_file *src)
197 {
198         memcpy(des->sf_uuid, src->sf_uuid, 16);
199         des->sf_flags   = cpu_to_le64(src->sf_flags);
200         des->sf_magic   = cpu_to_le32(src->sf_magic);
201         des->sf_status  = cpu_to_le16(src->sf_status);
202         des->sf_param   = cpu_to_le16(src->sf_param);
203         des->sf_time_last_complete      =
204                                 cpu_to_le64(src->sf_time_last_complete);
205         des->sf_time_latest_start       =
206                                 cpu_to_le64(src->sf_time_latest_start);
207         des->sf_time_last_checkpoint    =
208                                 cpu_to_le64(src->sf_time_last_checkpoint);
209         des->sf_pos_latest_start        =
210                                 cpu_to_le64(src->sf_pos_latest_start);
211         des->sf_pos_last_checkpoint     =
212                                 cpu_to_le64(src->sf_pos_last_checkpoint);
213         des->sf_pos_first_inconsistent  =
214                                 cpu_to_le64(src->sf_pos_first_inconsistent);
215         des->sf_items_checked           =
216                                 cpu_to_le64(src->sf_items_checked);
217         des->sf_items_updated           =
218                                 cpu_to_le64(src->sf_items_updated);
219         des->sf_items_failed            =
220                                 cpu_to_le64(src->sf_items_failed);
221         des->sf_items_updated_prior     =
222                                 cpu_to_le64(src->sf_items_updated_prior);
223         des->sf_run_time        = cpu_to_le32(src->sf_run_time);
224         des->sf_success_count   = cpu_to_le32(src->sf_success_count);
225         des->sf_oi_count        = cpu_to_le16(src->sf_oi_count);
226         memcpy(des->sf_oi_bitmap, src->sf_oi_bitmap, SCRUB_OI_BITMAP_SIZE);
227 }
228
229 static void osd_scrub_file_init(struct osd_scrub *scrub, __u8 *uuid)
230 {
231         struct scrub_file *sf = &scrub->os_file;
232
233         memset(sf, 0, sizeof(*sf));
234         memcpy(sf->sf_uuid, uuid, 16);
235         sf->sf_magic = SCRUB_MAGIC_V1;
236         sf->sf_status = SS_INIT;
237 }
238
239 void osd_scrub_file_reset(struct osd_scrub *scrub, __u8 *uuid, __u64 flags)
240 {
241         struct scrub_file *sf = &scrub->os_file;
242
243         CDEBUG(D_LFSCK, "Reset OI scrub file, flags = "LPX64"\n", flags);
244         memcpy(sf->sf_uuid, uuid, 16);
245         sf->sf_status = SS_INIT;
246         sf->sf_flags |= flags;
247         sf->sf_param = 0;
248         sf->sf_run_time = 0;
249         sf->sf_time_latest_start = 0;
250         sf->sf_time_last_checkpoint = 0;
251         sf->sf_pos_latest_start = 0;
252         sf->sf_pos_last_checkpoint = 0;
253         sf->sf_pos_first_inconsistent = 0;
254         sf->sf_items_checked = 0;
255         sf->sf_items_updated = 0;
256         sf->sf_items_failed = 0;
257         sf->sf_items_updated_prior = 0;
258         sf->sf_items_noscrub = 0;
259         sf->sf_items_igif = 0;
260 }
261
262 static int osd_scrub_file_load(struct osd_scrub *scrub)
263 {
264         loff_t  pos  = 0;
265         char   *name = LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name;
266         int     len  = sizeof(scrub->os_file_disk);
267         int     rc;
268
269         rc = osd_ldiskfs_read(scrub->os_inode, &scrub->os_file_disk, len, &pos);
270         if (rc == len) {
271                 struct scrub_file *sf = &scrub->os_file;
272
273                 osd_scrub_file_to_cpu(sf, &scrub->os_file_disk);
274                 if (sf->sf_magic != SCRUB_MAGIC_V1) {
275                         CWARN("%.16s: invalid scrub magic 0x%x != 0x%x\n,",
276                               name, sf->sf_magic, SCRUB_MAGIC_V1);
277                         /* Process it as new scrub file. */
278                         rc = -ENOENT;
279                 } else {
280                         rc = 0;
281                 }
282         } else if (rc != 0) {
283                 CERROR("%.16s: fail to load scrub file, expected = %d, "
284                        "rc = %d\n", name, len, rc);
285                 if (rc > 0)
286                         rc = -EFAULT;
287         } else {
288                 /* return -ENOENT for empty scrub file case. */
289                 rc = -ENOENT;
290         }
291
292         return rc;
293 }
294
295 int osd_scrub_file_store(struct osd_scrub *scrub)
296 {
297         struct osd_device *dev;
298         handle_t          *jh;
299         loff_t             pos     = 0;
300         int                len     = sizeof(scrub->os_file_disk);
301         int                credits;
302         int                rc;
303
304         dev = container_of0(scrub, struct osd_device, od_scrub);
305         credits = osd_dto_credits_noquota[DTO_WRITE_BASE] +
306                   osd_dto_credits_noquota[DTO_WRITE_BLOCK];
307         jh = ldiskfs_journal_start_sb(osd_sb(dev), credits);
308         if (IS_ERR(jh)) {
309                 rc = PTR_ERR(jh);
310                 CERROR("%.16s: fail to start trans for scrub store, rc = %d\n",
311                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,rc);
312                 return rc;
313         }
314
315         osd_scrub_file_to_le(&scrub->os_file_disk, &scrub->os_file);
316         rc = osd_ldiskfs_write_record(scrub->os_inode, &scrub->os_file_disk,
317                                       len, 0, &pos, jh);
318         ldiskfs_journal_stop(jh);
319         if (rc != 0)
320                 CERROR("%.16s: fail to store scrub file, expected = %d, "
321                        "rc = %d\n",
322                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
323                        len, rc);
324         scrub->os_time_last_checkpoint = cfs_time_current();
325         scrub->os_time_next_checkpoint = scrub->os_time_last_checkpoint +
326                                 cfs_time_seconds(SCRUB_CHECKPOINT_INTERVAL);
327         return rc;
328 }
329
330 /* OI scrub APIs */
331
332 static int osd_scrub_prep(struct osd_device *dev)
333 {
334         struct osd_scrub     *scrub  = &dev->od_scrub;
335         struct ptlrpc_thread *thread = &scrub->os_thread;
336         struct scrub_file    *sf     = &scrub->os_file;
337         __u32                 flags  = scrub->os_start_flags;
338         int                   rc;
339         ENTRY;
340
341         down_write(&scrub->os_rwsem);
342         if (flags & SS_SET_FAILOUT)
343                 sf->sf_param |= SP_FAILOUT;
344
345         if (flags & SS_CLEAR_FAILOUT)
346                 sf->sf_param &= ~SP_FAILOUT;
347
348         if (flags & SS_RESET)
349                 osd_scrub_file_reset(scrub,
350                         LDISKFS_SB(osd_sb(dev))->s_es->s_uuid, 0);
351
352         if (flags & SS_AUTO) {
353                 scrub->os_full_speed = 1;
354                 sf->sf_flags |= SF_AUTO;
355         } else {
356                 scrub->os_full_speed = 0;
357         }
358
359         if (sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT))
360                 scrub->os_full_speed = 1;
361
362         scrub->os_in_prior = 0;
363         scrub->os_waiting = 0;
364         scrub->os_paused = 0;
365         scrub->os_new_checked = 0;
366         if (sf->sf_pos_last_checkpoint != 0)
367                 sf->sf_pos_latest_start = sf->sf_pos_last_checkpoint + 1;
368         else
369                 sf->sf_pos_latest_start = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
370
371         scrub->os_pos_current = sf->sf_pos_latest_start;
372         sf->sf_status = SS_SCANNING;
373         sf->sf_time_latest_start = cfs_time_current_sec();
374         sf->sf_time_last_checkpoint = sf->sf_time_latest_start;
375         rc = osd_scrub_file_store(scrub);
376         if (rc == 0) {
377                 spin_lock(&scrub->os_lock);
378                 thread_set_flags(thread, SVC_RUNNING);
379                 spin_unlock(&scrub->os_lock);
380                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
381         }
382         up_write(&scrub->os_rwsem);
383
384         RETURN(rc);
385 }
386
387 static int
388 osd_scrub_check_update(struct osd_thread_info *info, struct osd_device *dev,
389                        struct osd_idmap_cache *oic, int val)
390 {
391         struct osd_scrub             *scrub  = &dev->od_scrub;
392         struct scrub_file            *sf     = &scrub->os_file;
393         struct lu_fid                *fid    = &oic->oic_fid;
394         struct osd_inode_id          *lid    = &oic->oic_lid;
395         struct osd_inode_id          *lid2   = &info->oti_id;
396         struct osd_inconsistent_item *oii    = NULL;
397         struct inode                 *inode  = NULL;
398         int                           ops    = DTO_INDEX_UPDATE;
399         int                           idx;
400         int                           rc;
401         ENTRY;
402
403         down_write(&scrub->os_rwsem);
404         scrub->os_new_checked++;
405         if (val < 0)
406                 GOTO(out, rc = val);
407
408         if (scrub->os_in_prior)
409                 oii = cfs_list_entry(oic, struct osd_inconsistent_item,
410                                      oii_cache);
411
412         if (lid->oii_ino < sf->sf_pos_latest_start && oii == NULL)
413                 GOTO(out, rc = 0);
414
415         if (fid_is_igif(fid))
416                 sf->sf_items_igif++;
417
418         if (val == SCRUB_NEXT_NOLMA && !dev->od_handle_nolma)
419                 GOTO(out, rc = 0);
420
421         if ((oii != NULL && oii->oii_insert) || (val == SCRUB_NEXT_NOLMA))
422                 goto iget;
423
424         /* XXX: Currently, no FID-in-LMA for OST object, so osd_oi_lookup()
425          *      wihtout checking FLD is enough.
426          *
427          *      It should be updated if FID-in-LMA for OSD object introduced
428          *      in the future. */
429         rc = osd_oi_lookup(info, dev, fid, lid2, false);
430         if (rc != 0) {
431                 if (rc != -ENOENT)
432                         GOTO(out, rc);
433
434 iget:
435                 inode = osd_iget(info, dev, lid);
436                 if (IS_ERR(inode)) {
437                         rc = PTR_ERR(inode);
438                         /* Someone removed the inode. */
439                         if (rc == -ENOENT || rc == -ESTALE)
440                                 rc = 0;
441                         GOTO(out, rc);
442                 }
443
444                 /* Prevent the inode to be unlinked during OI scrub. */
445                 mutex_lock(&inode->i_mutex);
446                 if (unlikely(inode->i_nlink == 0)) {
447                         mutex_unlock(&inode->i_mutex);
448                         iput(inode);
449                         GOTO(out, rc = 0);
450                 }
451
452                 ops = DTO_INDEX_INSERT;
453                 idx = osd_oi_fid2idx(dev, fid);
454                 sf->sf_flags |= SF_RECREATED | SF_INCONSISTENT;
455                 if (unlikely(!ldiskfs_test_bit(idx, sf->sf_oi_bitmap)))
456                         ldiskfs_set_bit(idx, sf->sf_oi_bitmap);
457         } else if (osd_id_eq(lid, lid2)) {
458                 GOTO(out, rc = 0);
459         } else {
460                 sf->sf_flags |= SF_INCONSISTENT;
461         }
462
463         rc = osd_scrub_refresh_mapping(info, dev, fid, lid, ops);
464         if (rc == 0) {
465                 if (scrub->os_in_prior)
466                         sf->sf_items_updated_prior++;
467                 else
468                         sf->sf_items_updated++;
469         }
470
471         GOTO(out, rc);
472
473 out:
474         if (rc < 0) {
475                 sf->sf_items_failed++;
476                 if (sf->sf_pos_first_inconsistent == 0 ||
477                     sf->sf_pos_first_inconsistent > lid->oii_ino)
478                         sf->sf_pos_first_inconsistent = lid->oii_ino;
479         } else {
480                 rc = 0;
481         }
482
483         if (ops == DTO_INDEX_INSERT) {
484                 mutex_unlock(&inode->i_mutex);
485                 iput(inode);
486         }
487         up_write(&scrub->os_rwsem);
488
489         if (oii != NULL) {
490                 LASSERT(!cfs_list_empty(&oii->oii_list));
491
492                 spin_lock(&scrub->os_lock);
493                 cfs_list_del_init(&oii->oii_list);
494                 spin_unlock(&scrub->os_lock);
495                 OBD_FREE_PTR(oii);
496         }
497         RETURN(sf->sf_param & SP_FAILOUT ? rc : 0);
498 }
499
500 static int osd_scrub_checkpoint(struct osd_scrub *scrub)
501 {
502         struct scrub_file *sf = &scrub->os_file;
503         int                rc;
504
505         if (likely(cfs_time_before(cfs_time_current(),
506                                    scrub->os_time_next_checkpoint) ||
507                    scrub->os_new_checked == 0))
508                 return 0;
509
510         down_write(&scrub->os_rwsem);
511         sf->sf_items_checked += scrub->os_new_checked;
512         scrub->os_new_checked = 0;
513         sf->sf_pos_last_checkpoint = scrub->os_pos_current;
514         sf->sf_time_last_checkpoint = cfs_time_current_sec();
515         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
516                                             scrub->os_time_last_checkpoint);
517         rc = osd_scrub_file_store(scrub);
518         up_write(&scrub->os_rwsem);
519
520         return rc;
521 }
522
523 static void osd_scrub_post(struct osd_scrub *scrub, int result)
524 {
525         struct scrub_file *sf = &scrub->os_file;
526         ENTRY;
527
528         down_write(&scrub->os_rwsem);
529         spin_lock(&scrub->os_lock);
530         thread_set_flags(&scrub->os_thread, SVC_STOPPING);
531         spin_unlock(&scrub->os_lock);
532         if (scrub->os_new_checked > 0) {
533                 sf->sf_items_checked += scrub->os_new_checked;
534                 scrub->os_new_checked = 0;
535                 sf->sf_pos_last_checkpoint = scrub->os_pos_current;
536         }
537         sf->sf_time_last_checkpoint = cfs_time_current_sec();
538         if (result > 0) {
539                 sf->sf_status = SS_COMPLETED;
540                 memset(sf->sf_oi_bitmap, 0, SCRUB_OI_BITMAP_SIZE);
541                 sf->sf_flags &= ~(SF_RECREATED | SF_INCONSISTENT | SF_AUTO);
542                 sf->sf_time_last_complete = sf->sf_time_last_checkpoint;
543                 sf->sf_success_count++;
544         } else if (result == 0) {
545                 if (scrub->os_paused)
546                         sf->sf_status = SS_PAUSED;
547                 else
548                         sf->sf_status = SS_STOPPED;
549         } else {
550                 sf->sf_status = SS_FAILED;
551         }
552         sf->sf_run_time += cfs_duration_sec(cfs_time_current() + HALF_SEC -
553                                             scrub->os_time_last_checkpoint);
554         result = osd_scrub_file_store(scrub);
555         if (result < 0)
556                 CERROR("%.16s: fail to osd_scrub_post, rc = %d\n",
557                        LDISKFS_SB(osd_scrub2sb(scrub))->s_es->s_volume_name,
558                        result);
559         up_write(&scrub->os_rwsem);
560
561         EXIT;
562 }
563
564 /* iteration engine */
565
566 struct osd_iit_param {
567         struct super_block *sb;
568         struct buffer_head *bitmap;
569         ldiskfs_group_t bg;
570         __u32 gbase;
571         __u32 offset;
572 };
573
574 typedef int (*osd_iit_next_policy)(struct osd_thread_info *info,
575                                    struct osd_device *dev,
576                                    struct osd_iit_param *param,
577                                    struct osd_idmap_cache **oic,
578                                    int noslot);
579
580 typedef int (*osd_iit_exec_policy)(struct osd_thread_info *info,
581                                    struct osd_device *dev,
582                                    struct osd_iit_param *param,
583                                    struct osd_idmap_cache *oic,
584                                    int *noslot, int rc);
585
586 static int osd_iit_next(struct osd_iit_param *param, __u32 *pos)
587 {
588         param->offset = ldiskfs_find_next_bit(param->bitmap->b_data,
589                         LDISKFS_INODES_PER_GROUP(param->sb), param->offset);
590         if (param->offset >= LDISKFS_INODES_PER_GROUP(param->sb)) {
591                 *pos = 1 + (param->bg+1) * LDISKFS_INODES_PER_GROUP(param->sb);
592                 return SCRUB_NEXT_BREAK;
593         } else {
594                 *pos = param->gbase + param->offset;
595                 return 0;
596         }
597 }
598
599 static int osd_iit_iget(struct osd_thread_info *info, struct osd_device *dev,
600                         struct lu_fid *fid, struct osd_inode_id *lid, __u32 pos,
601                         struct super_block *sb, bool scrub)
602 {
603         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
604         struct inode            *inode;
605         int                      rc;
606
607         osd_id_gen(lid, pos, OSD_OII_NOGEN);
608         inode = osd_iget(info, dev, lid);
609         if (IS_ERR(inode)) {
610                 rc = PTR_ERR(inode);
611                 /* The inode may be removed after bitmap searching, or the
612                  * file is new created without inode initialized yet. */
613                 if (rc == -ENOENT || rc == -ESTALE)
614                         return SCRUB_NEXT_CONTINUE;
615
616                 CERROR("%.16s: fail to read inode, ino# = %u, rc = %d\n",
617                        LDISKFS_SB(sb)->s_es->s_volume_name, pos, rc);
618                 return rc;
619         }
620
621         /* If the inode has no OI mapping, then it is special locally used,
622          * should be invisible to OI scrub or up layer LFSCK. */
623         if (ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI)) {
624                 iput(inode);
625                 return SCRUB_NEXT_CONTINUE;
626         }
627
628         if (scrub &&
629             ldiskfs_test_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB)) {
630                 /* Only skip it for the first OI scrub accessing. */
631                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
632                 iput(inode);
633                 return SCRUB_NEXT_NOSCRUB;
634         }
635
636         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
637         if (rc == 0) {
638                 if (!scrub) {
639                         if (!fid_is_client_visible(&lma->lma_self_fid))
640                                 rc = SCRUB_NEXT_CONTINUE;
641                         else
642                                 *fid = lma->lma_self_fid;
643                 }
644         } else if (rc == -ENODATA) {
645                 lu_igif_build(fid, inode->i_ino, inode->i_generation);
646                 if (scrub)
647                         rc = SCRUB_NEXT_NOLMA;
648                 else
649                         rc = 0;
650         }
651         iput(inode);
652         return rc;
653 }
654
655 static int osd_scrub_next(struct osd_thread_info *info, struct osd_device *dev,
656                           struct osd_iit_param *param,
657                           struct osd_idmap_cache **oic, int noslot)
658 {
659         struct osd_scrub     *scrub  = &dev->od_scrub;
660         struct ptlrpc_thread *thread = &scrub->os_thread;
661         struct lu_fid        *fid;
662         struct osd_inode_id  *lid;
663         int                   rc;
664
665         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_DELAY) && cfs_fail_val > 0) {
666                 struct l_wait_info lwi;
667
668                 lwi = LWI_TIMEOUT(cfs_time_seconds(cfs_fail_val), NULL, NULL);
669                 l_wait_event(thread->t_ctl_waitq,
670                              !cfs_list_empty(&scrub->os_inconsistent_items) ||
671                              !thread_is_running(thread),
672                              &lwi);
673         }
674
675         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_CRASH)) {
676                 spin_lock(&scrub->os_lock);
677                 thread_set_flags(thread, SVC_STOPPING);
678                 spin_unlock(&scrub->os_lock);
679                 return SCRUB_NEXT_CRASH;
680         }
681
682         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_SCRUB_FATAL))
683                 return SCRUB_NEXT_FATAL;
684
685         if (unlikely(!thread_is_running(thread)))
686                 return SCRUB_NEXT_EXIT;
687
688         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
689                 struct osd_inconsistent_item *oii;
690
691                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
692                                      struct osd_inconsistent_item, oii_list);
693                 *oic = &oii->oii_cache;
694                 scrub->os_in_prior = 1;
695                 return 0;
696         }
697
698         if (noslot != 0)
699                 return SCRUB_NEXT_WAIT;
700
701         rc = osd_iit_next(param, &scrub->os_pos_current);
702         if (rc != 0)
703                 return rc;
704
705         *oic = &scrub->os_oic;
706         fid = &(*oic)->oic_fid;
707         lid = &(*oic)->oic_lid;
708         rc = osd_iit_iget(info, dev, fid, lid,
709                           scrub->os_pos_current, param->sb, true);
710         return rc;
711 }
712
713 static int osd_preload_next(struct osd_thread_info *info,
714                             struct osd_device *dev, struct osd_iit_param *param,
715                             struct osd_idmap_cache **oic, int noslot)
716 {
717         struct osd_otable_cache *ooc    = &dev->od_otable_it->ooi_cache;
718         struct osd_scrub        *scrub;
719         struct ptlrpc_thread    *thread;
720         int                      rc;
721
722         rc = osd_iit_next(param, &ooc->ooc_pos_preload);
723         if (rc != 0)
724                 return rc;
725
726         scrub = &dev->od_scrub;
727         thread = &scrub->os_thread;
728         if (thread_is_running(thread) &&
729             ooc->ooc_pos_preload >= scrub->os_pos_current)
730                 return SCRUB_NEXT_EXIT;
731
732         rc = osd_iit_iget(info, dev,
733                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_fid,
734                           &ooc->ooc_cache[ooc->ooc_producer_idx].oic_lid,
735                           ooc->ooc_pos_preload, param->sb, false);
736         /* If succeed, it needs to move forward; otherwise up layer LFSCK may
737          * ignore the failure, so it still need to skip the inode next time. */
738         ooc->ooc_pos_preload = param->gbase + ++(param->offset);
739         return rc;
740 }
741
742 static int osd_scrub_exec(struct osd_thread_info *info, struct osd_device *dev,
743                           struct osd_iit_param *param,
744                           struct osd_idmap_cache *oic, int *noslot, int rc)
745 {
746         struct l_wait_info       lwi    = { 0 };
747         struct osd_scrub        *scrub  = &dev->od_scrub;
748         struct scrub_file       *sf     = &scrub->os_file;
749         struct ptlrpc_thread    *thread = &scrub->os_thread;
750         struct osd_otable_it    *it     = dev->od_otable_it;
751         struct osd_otable_cache *ooc    = it ? &it->ooi_cache : NULL;
752
753         switch (rc) {
754         case SCRUB_NEXT_CONTINUE:
755                 goto next;
756         case SCRUB_NEXT_WAIT:
757                 goto wait;
758         case SCRUB_NEXT_NOSCRUB:
759                 down_write(&scrub->os_rwsem);
760                 scrub->os_new_checked++;
761                 sf->sf_items_noscrub++;
762                 up_write(&scrub->os_rwsem);
763                 goto next;
764         }
765
766         rc = osd_scrub_check_update(info, dev, oic, rc);
767         if (rc != 0)
768                 return rc;
769
770         rc = osd_scrub_checkpoint(scrub);
771         if (rc != 0) {
772                 CERROR("%.16s: fail to checkpoint, pos = %u, rc = %d\n",
773                        LDISKFS_SB(param->sb)->s_es->s_volume_name,
774                        scrub->os_pos_current, rc);
775                 /* Continue, as long as the scrub itself can go ahead. */
776         }
777
778         if (scrub->os_in_prior) {
779                 scrub->os_in_prior = 0;
780                 return 0;
781         }
782
783 next:
784         scrub->os_pos_current = param->gbase + ++(param->offset);
785         if (it != NULL && it->ooi_waiting &&
786             ooc->ooc_pos_preload < scrub->os_pos_current) {
787                 it->ooi_waiting = 0;
788                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
789         }
790
791         if (scrub->os_full_speed || rc == SCRUB_NEXT_CONTINUE)
792                 return 0;
793
794 wait:
795         if (osd_scrub_has_window(scrub, ooc)) {
796                 *noslot = 0;
797                 return 0;
798         }
799
800         scrub->os_waiting = 1;
801         l_wait_event(thread->t_ctl_waitq,
802                      osd_scrub_has_window(scrub, ooc) ||
803                      !cfs_list_empty(&scrub->os_inconsistent_items) ||
804                      !thread_is_running(thread),
805                      &lwi);
806         scrub->os_waiting = 0;
807
808         if (osd_scrub_has_window(scrub, ooc))
809                 *noslot = 0;
810         else
811                 *noslot = 1;
812         return 0;
813 }
814
815 static int osd_preload_exec(struct osd_thread_info *info,
816                             struct osd_device *dev, struct osd_iit_param *param,
817                             struct osd_idmap_cache *oic, int *noslot, int rc)
818 {
819         struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
820
821         if (rc == 0) {
822                 ooc->ooc_cached_items++;
823                 ooc->ooc_producer_idx = (ooc->ooc_producer_idx + 1) &
824                                         ~OSD_OTABLE_IT_CACHE_MASK;
825         }
826         return rc > 0 ? 0 : rc;
827 }
828
829 #define SCRUB_IT_ALL    1
830 #define SCRUB_IT_CRASH  2
831
832 static int osd_inode_iteration(struct osd_thread_info *info,
833                                struct osd_device *dev, __u32 max, int preload)
834 {
835         osd_iit_next_policy   next;
836         osd_iit_exec_policy   exec;
837         __u32                *pos;
838         __u32                *count;
839         struct osd_iit_param  param;
840         __u32                 limit;
841         int                   noslot = 0;
842         int                   rc;
843         ENTRY;
844
845         if (preload == 0) {
846                 struct osd_scrub *scrub = &dev->od_scrub;
847
848                 next = osd_scrub_next;
849                 exec = osd_scrub_exec;
850                 pos = &scrub->os_pos_current;
851                 count = &scrub->os_new_checked;
852         } else {
853                 struct osd_otable_cache *ooc = &dev->od_otable_it->ooi_cache;
854
855                 next = osd_preload_next;
856                 exec = osd_preload_exec;
857                 pos = &ooc->ooc_pos_preload;
858                 count = &ooc->ooc_cached_items;
859         }
860         param.sb = osd_sb(dev);
861         limit = le32_to_cpu(LDISKFS_SB(param.sb)->s_es->s_inodes_count);
862
863         while (*pos <= limit && *count < max) {
864                 struct osd_idmap_cache *oic = NULL;
865
866                 param.bg = (*pos - 1) / LDISKFS_INODES_PER_GROUP(param.sb);
867                 param.offset = (*pos - 1) % LDISKFS_INODES_PER_GROUP(param.sb);
868                 param.gbase = 1 + param.bg * LDISKFS_INODES_PER_GROUP(param.sb);
869                 param.bitmap = ldiskfs_read_inode_bitmap(param.sb, param.bg);
870                 if (param.bitmap == NULL) {
871                         CERROR("%.16s: fail to read bitmap for %u, "
872                                "scrub will stop, urgent mode\n",
873                                LDISKFS_SB(param.sb)->s_es->s_volume_name,
874                                (__u32)param.bg);
875                         RETURN(-EIO);
876                 }
877
878                 while (param.offset < LDISKFS_INODES_PER_GROUP(param.sb) &&
879                        *count < max) {
880                         rc = next(info, dev, &param, &oic, noslot);
881                         switch (rc) {
882                         case SCRUB_NEXT_BREAK:
883                                 goto next_group;
884                         case SCRUB_NEXT_EXIT:
885                                 brelse(param.bitmap);
886                                 RETURN(0);
887                         case SCRUB_NEXT_CRASH:
888                                 brelse(param.bitmap);
889                                 RETURN(SCRUB_IT_CRASH);
890                         case SCRUB_NEXT_FATAL:
891                                 brelse(param.bitmap);
892                                 RETURN(-EINVAL);
893                         }
894
895                         rc = exec(info, dev, &param, oic, &noslot, rc);
896                         if (rc != 0) {
897                                 brelse(param.bitmap);
898                                 RETURN(rc);
899                         }
900                 }
901
902 next_group:
903                 brelse(param.bitmap);
904         }
905
906         if (*pos > limit)
907                 RETURN(SCRUB_IT_ALL);
908         RETURN(0);
909 }
910
911 static int osd_otable_it_preload(const struct lu_env *env,
912                                  struct osd_otable_it *it)
913 {
914         struct osd_device       *dev   = it->ooi_dev;
915         struct osd_scrub        *scrub = &dev->od_scrub;
916         struct osd_otable_cache *ooc   = &it->ooi_cache;
917         int                      rc;
918         ENTRY;
919
920         rc = osd_inode_iteration(osd_oti_get(env), dev,
921                                  OSD_OTABLE_IT_CACHE_SIZE, 1);
922         if (rc == SCRUB_IT_ALL)
923                 it->ooi_all_cached = 1;
924
925         CDEBUG(D_LFSCK, "OSD pre-loaded: max = %u, preload = %u, rc = %d\n",
926                le32_to_cpu(LDISKFS_SB(osd_sb(dev))->s_es->s_inodes_count),
927                ooc->ooc_pos_preload, rc);
928
929         if (scrub->os_waiting && osd_scrub_has_window(scrub, ooc)) {
930                 scrub->os_waiting = 0;
931                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
932         }
933
934         RETURN(rc < 0 ? rc : ooc->ooc_cached_items);
935 }
936
937 static int osd_scrub_main(void *args)
938 {
939         struct lu_env         env;
940         struct osd_device    *dev    = (struct osd_device *)args;
941         struct osd_scrub     *scrub  = &dev->od_scrub;
942         struct ptlrpc_thread *thread = &scrub->os_thread;
943         struct super_block   *sb     = osd_sb(dev);
944         int                   rc;
945         ENTRY;
946
947         cfs_daemonize("OI_scrub");
948         rc = lu_env_init(&env, LCT_DT_THREAD);
949         if (rc != 0) {
950                 CERROR("%.16s: OI scrub, fail to init env, rc = %d\n",
951                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
952                 GOTO(noenv, rc);
953         }
954
955         rc = osd_scrub_prep(dev);
956         if (rc != 0) {
957                 CERROR("%.16s: OI scrub, fail to scrub prep, rc = %d\n",
958                        LDISKFS_SB(sb)->s_es->s_volume_name, rc);
959                 GOTO(out, rc);
960         }
961
962         if (!scrub->os_full_speed) {
963                 struct l_wait_info lwi = { 0 };
964                 struct osd_otable_it *it = dev->od_otable_it;
965                 struct osd_otable_cache *ooc = &it->ooi_cache;
966
967                 l_wait_event(thread->t_ctl_waitq,
968                              it->ooi_user_ready || !thread_is_running(thread),
969                              &lwi);
970                 if (unlikely(!thread_is_running(thread)))
971                         GOTO(post, rc = 0);
972
973                 LASSERT(scrub->os_pos_current >= ooc->ooc_pos_preload);
974                 scrub->os_pos_current = ooc->ooc_pos_preload;
975         }
976
977         CDEBUG(D_LFSCK, "OI scrub: flags = 0x%x, pos = %u\n",
978                scrub->os_start_flags, scrub->os_pos_current);
979
980         rc = osd_inode_iteration(osd_oti_get(&env), dev, ~0U, 0);
981         if (unlikely(rc == SCRUB_IT_CRASH))
982                 GOTO(out, rc = -EINVAL);
983         GOTO(post, rc);
984
985 post:
986         osd_scrub_post(scrub, rc);
987         CDEBUG(D_LFSCK, "OI scrub: stop, rc = %d, pos = %u\n",
988                rc, scrub->os_pos_current);
989
990 out:
991         while (!cfs_list_empty(&scrub->os_inconsistent_items)) {
992                 struct osd_inconsistent_item *oii;
993
994                 oii = cfs_list_entry(scrub->os_inconsistent_items.next,
995                                      struct osd_inconsistent_item, oii_list);
996                 cfs_list_del_init(&oii->oii_list);
997                 OBD_FREE_PTR(oii);
998         }
999         lu_env_fini(&env);
1000
1001 noenv:
1002         spin_lock(&scrub->os_lock);
1003         thread_set_flags(thread, SVC_STOPPED);
1004         cfs_waitq_broadcast(&thread->t_ctl_waitq);
1005         spin_unlock(&scrub->os_lock);
1006         return rc;
1007 }
1008
1009 /* OI scrub start/stop */
1010
1011 static int do_osd_scrub_start(struct osd_device *dev, __u32 flags)
1012 {
1013         struct osd_scrub     *scrub  = &dev->od_scrub;
1014         struct ptlrpc_thread *thread = &scrub->os_thread;
1015         struct l_wait_info    lwi    = { 0 };
1016         int                   rc;
1017         ENTRY;
1018
1019 again:
1020         /* os_lock: sync status between stop and scrub thread */
1021         spin_lock(&scrub->os_lock);
1022         if (thread_is_running(thread)) {
1023                 spin_unlock(&scrub->os_lock);
1024                 RETURN(-EALREADY);
1025         } else if (unlikely(thread_is_stopping(thread))) {
1026                 spin_unlock(&scrub->os_lock);
1027                 l_wait_event(thread->t_ctl_waitq,
1028                              thread_is_stopped(thread),
1029                              &lwi);
1030                 goto again;
1031         }
1032         spin_unlock(&scrub->os_lock);
1033
1034         if (scrub->os_file.sf_status == SS_COMPLETED)
1035                 flags |= SS_RESET;
1036
1037         scrub->os_start_flags = flags;
1038         thread_set_flags(thread, 0);
1039         rc = cfs_create_thread(osd_scrub_main, dev, 0);
1040         if (rc < 0) {
1041                 CERROR("%.16s: cannot start iteration thread, rc = %d\n",
1042                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, rc);
1043                 RETURN(rc);
1044         }
1045
1046         l_wait_event(thread->t_ctl_waitq,
1047                      thread_is_running(thread) || thread_is_stopped(thread),
1048                      &lwi);
1049
1050         RETURN(0);
1051 }
1052
1053 int osd_scrub_start(struct osd_device *dev)
1054 {
1055         int rc;
1056         ENTRY;
1057
1058         /* od_otable_mutex: prevent curcurrent start/stop */
1059         mutex_lock(&dev->od_otable_mutex);
1060         rc = do_osd_scrub_start(dev, SS_AUTO);
1061         mutex_unlock(&dev->od_otable_mutex);
1062
1063         RETURN(rc == -EALREADY ? 0 : rc);
1064 }
1065
1066 static void do_osd_scrub_stop(struct osd_scrub *scrub)
1067 {
1068         struct ptlrpc_thread *thread = &scrub->os_thread;
1069         struct l_wait_info    lwi    = { 0 };
1070
1071         /* os_lock: sync status between stop and scrub thread */
1072         spin_lock(&scrub->os_lock);
1073         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1074                 thread_set_flags(thread, SVC_STOPPING);
1075                 spin_unlock(&scrub->os_lock);
1076                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
1077                 l_wait_event(thread->t_ctl_waitq,
1078                              thread_is_stopped(thread),
1079                              &lwi);
1080                 /* Do not skip the last lock/unlock, which can guarantee that
1081                  * the caller cannot return until the OI scrub thread exit. */
1082                 spin_lock(&scrub->os_lock);
1083         }
1084         spin_unlock(&scrub->os_lock);
1085 }
1086
1087 static void osd_scrub_stop(struct osd_device *dev)
1088 {
1089         /* od_otable_mutex: prevent curcurrent start/stop */
1090         mutex_lock(&dev->od_otable_mutex);
1091         dev->od_scrub.os_paused = 1;
1092         do_osd_scrub_stop(&dev->od_scrub);
1093         mutex_unlock(&dev->od_otable_mutex);
1094 }
1095
1096 /* OI scrub setup/cleanup */
1097
1098 static const char osd_scrub_name[] = "OI_scrub";
1099
1100 int osd_scrub_setup(const struct lu_env *env, struct osd_device *dev)
1101 {
1102         struct osd_thread_info     *info   = osd_oti_get(env);
1103         struct osd_scrub           *scrub  = &dev->od_scrub;
1104         struct lvfs_run_ctxt       *ctxt   = &scrub->os_ctxt;
1105         struct scrub_file          *sf     = &scrub->os_file;
1106         struct osd_inode_id        *id     = &scrub->os_oic.oic_lid;
1107         struct super_block         *sb     = osd_sb(dev);
1108         struct ldiskfs_super_block *es     = LDISKFS_SB(sb)->s_es;
1109         struct inode               *inode;
1110         struct lvfs_run_ctxt        saved;
1111         struct file                *filp;
1112         int                         dirty  = 0;
1113         int                         init   = 0;
1114         int                         rc     = 0;
1115         ENTRY;
1116
1117         memset(scrub, 0, sizeof(*scrub));
1118         OBD_SET_CTXT_MAGIC(ctxt);
1119         ctxt->pwdmnt = dev->od_mnt;
1120         ctxt->pwd = dev->od_mnt->mnt_root;
1121         ctxt->fs = get_ds();
1122
1123         cfs_waitq_init(&scrub->os_thread.t_ctl_waitq);
1124         init_rwsem(&scrub->os_rwsem);
1125         spin_lock_init(&scrub->os_lock);
1126         CFS_INIT_LIST_HEAD(&scrub->os_inconsistent_items);
1127
1128         push_ctxt(&saved, ctxt, NULL);
1129         filp = filp_open(osd_scrub_name, O_RDWR | O_CREAT, 0644);
1130         if (IS_ERR(filp))
1131                 RETURN(PTR_ERR(filp));
1132
1133         scrub->os_inode = igrab(filp->f_dentry->d_inode);
1134         filp_close(filp, 0);
1135         pop_ctxt(&saved, ctxt, NULL);
1136         ldiskfs_set_inode_state(scrub->os_inode,
1137                                 LDISKFS_STATE_LUSTRE_NO_OI);
1138
1139         rc = osd_scrub_file_load(scrub);
1140         if (rc == -ENOENT) {
1141                 osd_scrub_file_init(scrub, es->s_uuid);
1142                 dirty = 1;
1143                 init = 1;
1144         } else if (rc != 0) {
1145                 RETURN(rc);
1146         } else {
1147                 if (memcmp(sf->sf_uuid, es->s_uuid, 16) != 0) {
1148                         osd_scrub_file_reset(scrub, es->s_uuid,SF_INCONSISTENT);
1149                         dirty = 1;
1150                 } else if (sf->sf_status == SS_SCANNING) {
1151                         sf->sf_status = SS_CRASHED;
1152                         dirty = 1;
1153                 }
1154         }
1155
1156         if (sf->sf_pos_last_checkpoint != 0)
1157                 scrub->os_pos_current = sf->sf_pos_last_checkpoint + 1;
1158         else
1159                 scrub->os_pos_current = LDISKFS_FIRST_INO(sb) + 1;
1160
1161         if (dirty != 0) {
1162                 rc = osd_scrub_file_store(scrub);
1163                 if (rc != 0)
1164                         RETURN(rc);
1165         }
1166
1167         /* Initialize OI files. */
1168         rc = osd_oi_init(info, dev);
1169         if (rc < 0)
1170                 RETURN(rc);
1171
1172         if (init != 0) {
1173                 rc = __osd_oi_lookup(info, dev, &LU_DOT_LUSTRE_FID, id);
1174                 if (rc == 0) {
1175                         inode = osd_iget(info, dev, id);
1176                         if (IS_ERR(inode)) {
1177                                 rc = PTR_ERR(inode);
1178                                 /* It is restored from old 2.x backup. */
1179                                 if (rc == -ENOENT || rc == -ESTALE) {
1180                                         osd_scrub_file_reset(scrub, es->s_uuid,
1181                                                              SF_INCONSISTENT);
1182                                         rc = osd_scrub_file_store(scrub);
1183                                 }
1184                         } else {
1185                                 iput(inode);
1186                         }
1187                 } else if (rc == -ENOENT) {
1188                         rc = 0;
1189                 }
1190         }
1191
1192         if (rc == 0 && !dev->od_noscrub &&
1193             ((sf->sf_status == SS_PAUSED) ||
1194              (sf->sf_status == SS_CRASHED &&
1195               sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT | SF_AUTO)) ||
1196              (sf->sf_status == SS_INIT &&
1197               sf->sf_flags & (SF_RECREATED | SF_INCONSISTENT))))
1198                 rc = osd_scrub_start(dev);
1199
1200         RETURN(rc);
1201 }
1202
1203 void osd_scrub_cleanup(const struct lu_env *env, struct osd_device *dev)
1204 {
1205         struct osd_scrub *scrub = &dev->od_scrub;
1206
1207         LASSERT(dev->od_otable_it == NULL);
1208
1209         if (scrub->os_inode != NULL) {
1210                 osd_scrub_stop(dev);
1211                 iput(scrub->os_inode);
1212                 scrub->os_inode = NULL;
1213         }
1214         if (dev->od_oi_table != NULL)
1215                 osd_oi_fini(osd_oti_get(env), dev);
1216 }
1217
1218 /* object table based iteration APIs */
1219
1220 static struct dt_it *osd_otable_it_init(const struct lu_env *env,
1221                                        struct dt_object *dt, __u32 attr,
1222                                        struct lustre_capa *capa)
1223 {
1224         enum dt_otable_it_flags flags = attr >> DT_OTABLE_IT_FLAGS_SHIFT;
1225         enum dt_otable_it_valid valid = attr & ~DT_OTABLE_IT_FLAGS_MASK;
1226         struct osd_device      *dev   = osd_dev(dt->do_lu.lo_dev);
1227         struct osd_scrub       *scrub = &dev->od_scrub;
1228         struct osd_otable_it   *it;
1229         __u32                   start = 0;
1230         int                     rc;
1231         ENTRY;
1232
1233         /* od_otable_mutex: prevent curcurrent init/fini */
1234         mutex_lock(&dev->od_otable_mutex);
1235         if (dev->od_otable_it != NULL)
1236                 GOTO(out, it = ERR_PTR(-EALREADY));
1237
1238         OBD_ALLOC_PTR(it);
1239         if (it == NULL)
1240                 GOTO(out, it = ERR_PTR(-ENOMEM));
1241
1242         dev->od_otable_it = it;
1243         it->ooi_dev = dev;
1244         it->ooi_cache.ooc_consumer_idx = -1;
1245         if (flags & DOIF_OUTUSED)
1246                 it->ooi_used_outside = 1;
1247
1248         if (flags & DOIF_RESET)
1249                 start |= SS_RESET;
1250
1251         if (valid & DOIV_ERROR_HANDLE) {
1252                 if (flags & DOIF_FAILOUT)
1253                         start |= SS_SET_FAILOUT;
1254                 else
1255                         start |= SS_CLEAR_FAILOUT;
1256         }
1257
1258         rc = do_osd_scrub_start(dev, start);
1259         if (rc == -EALREADY) {
1260                 it->ooi_cache.ooc_pos_preload = scrub->os_pos_current - 1;
1261         } else if (rc < 0) {
1262                 dev->od_otable_it = NULL;
1263                 OBD_FREE_PTR(it);
1264                 GOTO(out, it = ERR_PTR(-EALREADY));
1265         } else {
1266                 it->ooi_cache.ooc_pos_preload = scrub->os_pos_current;
1267         }
1268
1269         GOTO(out, it);
1270
1271 out:
1272         mutex_unlock(&dev->od_otable_mutex);
1273         return (struct dt_it *)it;
1274 }
1275
1276 static void osd_otable_it_fini(const struct lu_env *env, struct dt_it *di)
1277 {
1278         struct osd_otable_it *it  = (struct osd_otable_it *)di;
1279         struct osd_device    *dev = it->ooi_dev;
1280
1281         /* od_otable_mutex: prevent curcurrent init/fini */
1282         mutex_lock(&dev->od_otable_mutex);
1283         do_osd_scrub_stop(&dev->od_scrub);
1284         LASSERT(dev->od_otable_it == it);
1285
1286         dev->od_otable_it = NULL;
1287         mutex_unlock(&dev->od_otable_mutex);
1288         OBD_FREE_PTR(it);
1289 }
1290
1291 /**
1292  * XXX: Temporary used to notify otable iteration to be paused.
1293  */
1294 static void osd_otable_it_put(const struct lu_env *env, struct dt_it *di)
1295 {
1296         struct osd_device *dev = ((struct osd_otable_it *)di)->ooi_dev;
1297
1298         /* od_otable_mutex: prevent curcurrent init/fini */
1299         mutex_lock(&dev->od_otable_mutex);
1300         dev->od_scrub.os_paused = 1;
1301         mutex_unlock(&dev->od_otable_mutex);
1302 }
1303
1304 /**
1305  * Set the OSD layer iteration start position as the specified key.
1306  *
1307  * The LFSCK out of OSD layer does not know the detail of the key, so if there
1308  * are several keys, they cannot be compared out of OSD, so call "::get()" for
1309  * each key, and OSD will select the smallest one by itself.
1310  */
1311 static int osd_otable_it_get(const struct lu_env *env,
1312                              struct dt_it *di, const struct dt_key *key)
1313 {
1314         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
1315         struct osd_otable_cache *ooc = &it->ooi_cache;
1316         const char              *str = (const char *)key;
1317         __u32                    ino;
1318         ENTRY;
1319
1320         /* Forbid to set iteration position after iteration started. */
1321         if (it->ooi_user_ready)
1322                 RETURN(-EPERM);
1323
1324         if (str[0] == '\0')
1325                 RETURN(-EINVAL);
1326
1327         if (sscanf(str, "%u", &ino) <= 0)
1328                 RETURN(-EINVAL);
1329
1330         /* Skip the one that has been processed last time. */
1331         if (ooc->ooc_pos_preload > ++ino)
1332                 ooc->ooc_pos_preload = ino;
1333
1334         RETURN(0);
1335 }
1336
1337 static int osd_otable_it_next(const struct lu_env *env, struct dt_it *di)
1338 {
1339         struct osd_otable_it    *it     = (struct osd_otable_it *)di;
1340         struct osd_device       *dev    = it->ooi_dev;
1341         struct osd_scrub        *scrub  = &dev->od_scrub;
1342         struct osd_otable_cache *ooc    = &it->ooi_cache;
1343         struct ptlrpc_thread    *thread = &scrub->os_thread;
1344         struct l_wait_info       lwi    = { 0 };
1345         int                      rc;
1346         ENTRY;
1347
1348         LASSERT(it->ooi_user_ready);
1349
1350 again:
1351         if (!thread_is_running(thread) && !it->ooi_used_outside)
1352                 RETURN(1);
1353
1354         if (ooc->ooc_cached_items > 0) {
1355                 ooc->ooc_cached_items--;
1356                 ooc->ooc_consumer_idx = (ooc->ooc_consumer_idx + 1) &
1357                                         ~OSD_OTABLE_IT_CACHE_MASK;
1358                 RETURN(0);
1359         }
1360
1361         if (it->ooi_all_cached) {
1362                 l_wait_event(thread->t_ctl_waitq,
1363                              !thread_is_running(thread),
1364                              &lwi);
1365                 RETURN(1);
1366         }
1367
1368         it->ooi_waiting = 1;
1369         l_wait_event(thread->t_ctl_waitq,
1370                      ooc->ooc_pos_preload < scrub->os_pos_current ||
1371                      !thread_is_running(thread),
1372                      &lwi);
1373         it->ooi_waiting = 0;
1374
1375         if (!thread_is_running(thread) && !it->ooi_used_outside)
1376                 RETURN(1);
1377
1378         rc = osd_otable_it_preload(env, it);
1379         if (rc >= 0)
1380                 goto again;
1381
1382         RETURN(rc);
1383 }
1384
1385 static struct dt_key *osd_otable_it_key(const struct lu_env *env,
1386                                         const struct dt_it *di)
1387 {
1388         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
1389         struct osd_otable_cache *ooc = &it->ooi_cache;
1390
1391         sprintf(it->ooi_key, "%u",
1392                 ooc->ooc_cache[ooc->ooc_consumer_idx].oic_lid.oii_ino);
1393         return (struct dt_key *)it->ooi_key;
1394 }
1395
1396 static int osd_otable_it_key_size(const struct lu_env *env,
1397                                   const struct dt_it *di)
1398 {
1399         return sizeof(((struct osd_otable_it *)di)->ooi_key);
1400 }
1401
1402 static int osd_otable_it_rec(const struct lu_env *env, const struct dt_it *di,
1403                              struct dt_rec *rec, __u32 attr)
1404 {
1405         struct osd_otable_it    *it  = (struct osd_otable_it *)di;
1406         struct osd_otable_cache *ooc = &it->ooi_cache;
1407
1408         *(struct lu_fid *)rec = ooc->ooc_cache[ooc->ooc_consumer_idx].oic_fid;
1409         return 0;
1410 }
1411
1412 static int osd_otable_it_load(const struct lu_env *env,
1413                               const struct dt_it *di, __u64 hash)
1414 {
1415         struct osd_otable_it    *it    = (struct osd_otable_it *)di;
1416         struct osd_device       *dev   = it->ooi_dev;
1417         struct osd_otable_cache *ooc   = &it->ooi_cache;
1418         struct osd_scrub        *scrub = &dev->od_scrub;
1419
1420         if (it->ooi_user_ready)
1421                 return 0;
1422
1423         if (ooc->ooc_pos_preload <= LDISKFS_FIRST_INO(osd_sb(dev)))
1424                 ooc->ooc_pos_preload = LDISKFS_FIRST_INO(osd_sb(dev)) + 1;
1425         it->ooi_user_ready = 1;
1426         if (!scrub->os_full_speed)
1427                 cfs_waitq_broadcast(&scrub->os_thread.t_ctl_waitq);
1428
1429         /* Unplug OSD layer iteration by the first next() call. */
1430         return osd_otable_it_next(env, (struct dt_it *)it);
1431 }
1432
1433 const struct dt_index_operations osd_otable_ops = {
1434         .dio_it = {
1435                 .init     = osd_otable_it_init,
1436                 .fini     = osd_otable_it_fini,
1437                 .put      = osd_otable_it_put,
1438                 .get      = osd_otable_it_get,
1439                 .next     = osd_otable_it_next,
1440                 .key      = osd_otable_it_key,
1441                 .key_size = osd_otable_it_key_size,
1442                 .rec      = osd_otable_it_rec,
1443                 .load     = osd_otable_it_load,
1444         }
1445 };
1446
1447 /* high priority inconsistent items list APIs */
1448
1449 int osd_oii_insert(struct osd_device *dev, struct osd_idmap_cache *oic,
1450                    int insert)
1451 {
1452         struct osd_inconsistent_item *oii;
1453         struct osd_scrub             *scrub  = &dev->od_scrub;
1454         struct ptlrpc_thread         *thread = &scrub->os_thread;
1455         int                           wakeup = 0;
1456         ENTRY;
1457
1458         OBD_ALLOC_PTR(oii);
1459         if (unlikely(oii == NULL))
1460                 RETURN(-ENOMEM);
1461
1462         CFS_INIT_LIST_HEAD(&oii->oii_list);
1463         oii->oii_cache = *oic;
1464         oii->oii_insert = insert;
1465
1466         spin_lock(&scrub->os_lock);
1467         if (unlikely(!thread_is_running(thread))) {
1468                 spin_unlock(&scrub->os_lock);
1469                 OBD_FREE_PTR(oii);
1470                 RETURN(-EAGAIN);
1471         }
1472
1473         if (cfs_list_empty(&scrub->os_inconsistent_items))
1474                 wakeup = 1;
1475         cfs_list_add_tail(&oii->oii_list, &scrub->os_inconsistent_items);
1476         spin_unlock(&scrub->os_lock);
1477
1478         if (wakeup != 0)
1479                 cfs_waitq_broadcast(&thread->t_ctl_waitq);
1480
1481         RETURN(0);
1482 }
1483
1484 int osd_oii_lookup(struct osd_device *dev, const struct lu_fid *fid,
1485                    struct osd_inode_id *id)
1486 {
1487         struct osd_scrub             *scrub = &dev->od_scrub;
1488         struct osd_inconsistent_item *oii;
1489         ENTRY;
1490
1491         spin_lock(&scrub->os_lock);
1492         cfs_list_for_each_entry(oii, &scrub->os_inconsistent_items, oii_list) {
1493                 if (lu_fid_eq(fid, &oii->oii_cache.oic_fid)) {
1494                         *id = oii->oii_cache.oic_lid;
1495                         spin_unlock(&scrub->os_lock);
1496                         RETURN(0);
1497                 }
1498         }
1499         spin_unlock(&scrub->os_lock);
1500
1501         RETURN(-ENOENT);
1502 }
1503
1504 /* OI scrub dump */
1505
1506 static const char *scrub_status_names[] = {
1507         "init",
1508         "scanning",
1509         "completed",
1510         "failed",
1511         "stopped",
1512         "paused",
1513         "crashed",
1514         NULL
1515 };
1516
1517 static const char *scrub_flags_names[] = {
1518         "recreated",
1519         "inconsistent",
1520         "auto",
1521         NULL
1522 };
1523
1524 static const char *scrub_param_names[] = {
1525         "failout",
1526         NULL
1527 };
1528
1529 static int scrub_bits_dump(char **buf, int *len, int bits, const char *names[],
1530                            const char *prefix)
1531 {
1532         int save = *len;
1533         int flag;
1534         int rc;
1535         int i;
1536
1537         rc = snprintf(*buf, *len, "%s:%c", prefix, bits != 0 ? ' ' : '\n');
1538         if (rc <= 0)
1539                 return -ENOSPC;
1540
1541         *buf += rc;
1542         *len -= rc;
1543         for (i = 0, flag = 1; bits != 0; i++, flag = 1 << i) {
1544                 if (flag & bits) {
1545                         bits &= ~flag;
1546                         rc = snprintf(*buf, *len, "%s%c", names[i],
1547                                       bits != 0 ? ',' : '\n');
1548                         if (rc <= 0)
1549                                 return -ENOSPC;
1550
1551                         *buf += rc;
1552                         *len -= rc;
1553                 }
1554         }
1555         return save - *len;
1556 }
1557
1558 static int scrub_time_dump(char **buf, int *len, __u64 time, const char *prefix)
1559 {
1560         int rc;
1561
1562         if (time != 0)
1563                 rc = snprintf(*buf, *len, "%s: "LPU64" seconds\n", prefix,
1564                               cfs_time_current_sec() - time);
1565         else
1566                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
1567         if (rc <= 0)
1568                 return -ENOSPC;
1569
1570         *buf += rc;
1571         *len -= rc;
1572         return rc;
1573 }
1574
1575 static int scrub_pos_dump(char **buf, int *len, __u64 pos, const char *prefix)
1576 {
1577         int rc;
1578
1579         if (pos != 0)
1580                 rc = snprintf(*buf, *len, "%s: "LPU64"\n", prefix, pos);
1581         else
1582                 rc = snprintf(*buf, *len, "%s: N/A\n", prefix);
1583         if (rc <= 0)
1584                 return -ENOSPC;
1585
1586         *buf += rc;
1587         *len -= rc;
1588         return rc;
1589 }
1590
1591 int osd_scrub_dump(struct osd_device *dev, char *buf, int len)
1592 {
1593         struct osd_scrub  *scrub   = &dev->od_scrub;
1594         struct scrub_file *sf      = &scrub->os_file;
1595         __u64              checked;
1596         __u64              speed;
1597         int                save    = len;
1598         int                ret     = -ENOSPC;
1599         int                rc;
1600
1601         down_read(&scrub->os_rwsem);
1602         rc = snprintf(buf, len,
1603                       "name: OI_scrub\n"
1604                       "magic: 0x%x\n"
1605                       "oi_files: %d\n"
1606                       "status: %s\n",
1607                       sf->sf_magic, (int)sf->sf_oi_count,
1608                       scrub_status_names[sf->sf_status]);
1609         if (rc <= 0)
1610                 goto out;
1611
1612         buf += rc;
1613         len -= rc;
1614         rc = scrub_bits_dump(&buf, &len, sf->sf_flags, scrub_flags_names,
1615                              "flags");
1616         if (rc < 0)
1617                 goto out;
1618
1619         rc = scrub_bits_dump(&buf, &len, sf->sf_param, scrub_param_names,
1620                              "param");
1621         if (rc < 0)
1622                 goto out;
1623
1624         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_complete,
1625                              "time_since_last_completed");
1626         if (rc < 0)
1627                 goto out;
1628
1629         rc = scrub_time_dump(&buf, &len, sf->sf_time_latest_start,
1630                              "time_since_latest_start");
1631         if (rc < 0)
1632                 goto out;
1633
1634         rc = scrub_time_dump(&buf, &len, sf->sf_time_last_checkpoint,
1635                              "time_since_last_checkpoint");
1636         if (rc < 0)
1637                 goto out;
1638
1639         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_latest_start,
1640                             "latest_start_position");
1641         if (rc < 0)
1642                 goto out;
1643
1644         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_last_checkpoint,
1645                             "last_checkpoint_position");
1646         if (rc < 0)
1647                 goto out;
1648
1649         rc = scrub_pos_dump(&buf, &len, sf->sf_pos_first_inconsistent,
1650                             "first_failure_position");
1651         if (rc < 0)
1652                 goto out;
1653
1654         checked = sf->sf_items_checked + scrub->os_new_checked;
1655         rc = snprintf(buf, len,
1656                       "checked: "LPU64"\n"
1657                       "updated: "LPU64"\n"
1658                       "failed: "LPU64"\n"
1659                       "prior_updated: "LPU64"\n"
1660                       "noscrub: "LPU64"\n"
1661                       "igif: "LPU64"\n"
1662                       "success_count: %u\n",
1663                       checked, sf->sf_items_updated, sf->sf_items_failed,
1664                       sf->sf_items_updated_prior, sf->sf_items_noscrub,
1665                       sf->sf_items_igif, sf->sf_success_count);
1666         if (rc <= 0)
1667                 goto out;
1668
1669         buf += rc;
1670         len -= rc;
1671         speed = checked;
1672         if (thread_is_running(&scrub->os_thread)) {
1673                 cfs_duration_t duration = cfs_time_current() -
1674                                           scrub->os_time_last_checkpoint;
1675                 __u64 new_checked = scrub->os_new_checked * CFS_HZ;
1676                 __u32 rtime = sf->sf_run_time +
1677                               cfs_duration_sec(duration + HALF_SEC);
1678
1679                 if (duration != 0)
1680                         do_div(new_checked, duration);
1681                 if (rtime != 0)
1682                         do_div(speed, rtime);
1683                 rc = snprintf(buf, len,
1684                               "run_time: %u seconds\n"
1685                               "average_speed: "LPU64" objects/sec\n"
1686                               "real-time_speed: "LPU64" objects/sec\n"
1687                               "current_position: %u\n",
1688                               rtime, speed, new_checked, scrub->os_pos_current);
1689         } else {
1690                 if (sf->sf_run_time != 0)
1691                         do_div(speed, sf->sf_run_time);
1692                 rc = snprintf(buf, len,
1693                               "run_time: %u seconds\n"
1694                               "average_speed: "LPU64" objects/sec\n"
1695                               "real-time_speed: N/A\n"
1696                               "current_position: N/A\n",
1697                               sf->sf_run_time, speed);
1698         }
1699         if (rc <= 0)
1700                 goto out;
1701
1702         buf += rc;
1703         len -= rc;
1704         ret = save - len;
1705
1706 out:
1707         up_read(&scrub->os_rwsem);
1708         return ret;
1709 }