Whamcloud - gitweb
47ec49cef218dc7ae1f8d2d489cf7a05455df4d7
[fs/lustre-release.git] / lustre / osp / osp_sync.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, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osp/osp_sync.c
33  *
34  * Lustre OST Proxy Device
35  *
36  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
37  * Author: Mikhail Pershin <mike.pershin@intel.com>
38  */
39
40 #define DEBUG_SUBSYSTEM S_MDS
41
42 #include <linux/kthread.h>
43 #include <lustre_log.h>
44 #include <lustre_update.h>
45 #include "osp_internal.h"
46
47 /*
48  * this is a components of OSP implementing synchronization between MDS and OST
49  * it llogs all interesting changes (currently it's uig/gid change and object
50  * destroy) atomically, then makes sure changes hit OST storage
51  *
52  * we have 4 queues of work:
53  *
54  * the first queue is llog itself, once read a change is stored in 2nd queue
55  * in form of RPC (but RPC isn't fired yet).
56  *
57  * the second queue (opd_sync_waiting_for_commit) holds changes awaiting local
58  * commit. once change is committed locally it migrates onto 3rd queue.
59  *
60  * the third queue (opd_sync_committed_here) holds changes committed locally,
61  * but not sent to OST (as the pipe can be full). once pipe becomes non-full
62  * we take a change from the queue and fire corresponded RPC.
63  *
64  * once RPC is reported committed by OST (using regular last_committed mech.)
65  * the change jumps into 4th queue (opd_sync_committed_there), now we can
66  * cancel corresponded llog record and release RPC
67  *
68  * opd_sync_changes is a number of unread llog records (to be processed).
69  * notice this number doesn't include llog records from previous boots.
70  * with OSP_SYNC_THRESHOLD we try to batch processing a bit (TO BE IMPLEMENTED)
71  *
72  * opd_sync_rpcs_in_progress is total number of requests in above 2-4 queues.
73  * we control this with OSP_MAX_RPCS_IN_PROGRESS so that OSP don't consume
74  * too much memory -- how to deal with 1000th OSTs ? batching could help?
75  *
76  * opd_sync_rpcs_in_flight is a number of RPC in flight.
77  * we control this with OSP_MAX_RPCS_IN_FLIGHT
78  */
79
80 /* XXX: do math to learn reasonable threshold
81  * should it be ~ number of changes fitting bulk? */
82
83 #define OSP_SYNC_THRESHOLD              10
84 #define OSP_MAX_RPCS_IN_FLIGHT          8
85 #define OSP_MAX_RPCS_IN_PROGRESS        4096
86
87 #define OSP_JOB_MAGIC           0x26112005
88
89 struct osp_job_req_args {
90         /** bytes reserved for ptlrpc_replay_req() */
91         struct ptlrpc_replay_async_args jra_raa;
92         struct list_head                jra_committed_link;
93         struct list_head                jra_in_flight_link;
94         struct llog_cookie              jra_lcookie;
95         __u32                           jra_magic;
96 };
97
98 static inline int osp_sync_running(struct osp_device *d)
99 {
100         return !!(d->opd_sync_thread.t_flags & SVC_RUNNING);
101 }
102
103 /**
104  * Check status: whether OSP thread has stopped
105  *
106  * \param[in] d         OSP device
107  *
108  * \retval 0            still running
109  * \retval 1            stopped
110  */
111 static inline int osp_sync_stopped(struct osp_device *d)
112 {
113         return !!(d->opd_sync_thread.t_flags & SVC_STOPPED);
114 }
115
116 /*
117  ** Check for new changes to sync
118  *
119  * \param[in] d         OSP device
120  *
121  * \retval 1            there are changes
122  * \retval 0            there are no changes
123  */
124 static inline int osp_sync_has_new_job(struct osp_device *d)
125 {
126         return atomic_read(&d->opd_sync_changes) > 0 ||
127                 d->opd_sync_prev_done == 0;
128 }
129
130 static inline int osp_sync_in_flight_conflict(struct osp_device *d,
131                                              struct llog_rec_hdr *h)
132 {
133         struct osp_job_req_args *jra;
134         struct ost_id            ostid;
135         int                      conflict = 0;
136
137         if (h == NULL || h->lrh_type == LLOG_GEN_REC ||
138             list_empty(&d->opd_sync_in_flight_list))
139                 return conflict;
140
141         memset(&ostid, 0, sizeof(ostid));
142         switch (h->lrh_type) {
143         case MDS_UNLINK_REC: {
144                 struct llog_unlink_rec *unlink = (struct llog_unlink_rec *)h;
145
146                 ostid_set_seq(&ostid, unlink->lur_oseq);
147                 if (ostid_set_id(&ostid, unlink->lur_oid)) {
148                         CERROR("Bad %llu to set " DOSTID "\n",
149                                (unsigned long long)(unlink->lur_oid),
150                                POSTID(&ostid));
151                         return 1;
152                 }
153                 }
154                 break;
155         case MDS_UNLINK64_REC:
156                 fid_to_ostid(&((struct llog_unlink64_rec *)h)->lur_fid, &ostid);
157                 break;
158         case MDS_SETATTR64_REC:
159                 ostid = ((struct llog_setattr64_rec *)h)->lsr_oi;
160                 break;
161         default:
162                 LBUG();
163         }
164
165         spin_lock(&d->opd_sync_lock);
166         list_for_each_entry(jra, &d->opd_sync_in_flight_list,
167                             jra_in_flight_link) {
168                 struct ptlrpc_request   *req;
169                 struct ost_body         *body;
170
171                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
172
173                 req = container_of((void *)jra, struct ptlrpc_request,
174                                    rq_async_args);
175                 body = req_capsule_client_get(&req->rq_pill,
176                                               &RMF_OST_BODY);
177                 LASSERT(body);
178
179                 if (memcmp(&ostid, &body->oa.o_oi, sizeof(ostid)) == 0) {
180                         conflict = 1;
181                         break;
182                 }
183         }
184         spin_unlock(&d->opd_sync_lock);
185
186         return conflict;
187 }
188
189 static inline int osp_sync_rpcs_in_progress_low(struct osp_device *d)
190 {
191         return atomic_read(&d->opd_sync_rpcs_in_progress) <
192                 d->opd_sync_max_rpcs_in_progress;
193 }
194
195 /**
196  * Check for room in the network pipe to OST
197  *
198  * \param[in] d         OSP device
199  *
200  * \retval 1            there is room
201  * \retval 0            no room, the pipe is full
202  */
203 static inline int osp_sync_rpcs_in_flight_low(struct osp_device *d)
204 {
205         return atomic_read(&d->opd_sync_rpcs_in_flight) <
206                 d->opd_sync_max_rpcs_in_flight;
207 }
208
209 /**
210  * Wake up check for the main sync thread
211  *
212  * \param[in] d         OSP device
213  *
214  * \retval 1            time to wake up
215  * \retval 0            no need to wake up
216  */
217 static inline int osp_sync_has_work(struct osp_device *osp)
218 {
219         /* has new/old changes and low in-progress? */
220         if (osp_sync_has_new_job(osp) && osp_sync_rpcs_in_progress_low(osp) &&
221             osp_sync_rpcs_in_flight_low(osp) && osp->opd_imp_connected)
222                 return 1;
223
224         /* has remotely committed? */
225         if (!list_empty(&osp->opd_sync_committed_there))
226                 return 1;
227
228         return 0;
229 }
230
231 void osp_sync_check_for_work(struct osp_device *osp)
232 {
233         if (osp_sync_has_work(osp))
234                 wake_up(&osp->opd_sync_waitq);
235 }
236
237 static inline __u64 osp_sync_correct_id(struct osp_device *d,
238                                         struct llog_rec_hdr *rec)
239 {
240         /*
241          * llog use cyclic store with 32 bit lrh_id
242          * so overflow lrh_id is possible. Range between
243          * last_processed and last_committed is less than
244          * 64745 ^ 2 and less than 2^32 - 1
245          */
246         __u64 correct_id = d->opd_sync_last_committed_id;
247
248         if ((correct_id & 0xffffffffULL) < rec->lrh_id)
249                 correct_id -= 0x100000000ULL;
250
251         correct_id &= ~0xffffffffULL;
252         correct_id |= rec->lrh_id;
253
254         return correct_id;
255 }
256
257 /**
258  * Check and return ready-for-new status.
259  *
260  * The thread processing llog record uses this function to check whether
261  * it's time to take another record and process it. The number of conditions
262  * must be met: the connection should be ready, RPCs in flight not exceeding
263  * the limit, the record is committed locally, etc (see the lines below).
264  *
265  * \param[in] d         OSP device
266  * \param[in] rec       next llog record to process
267  *
268  * \retval 0            not ready
269  * \retval 1            ready
270  */
271 static inline int osp_sync_can_process_new(struct osp_device *d,
272                                            struct llog_rec_hdr *rec)
273 {
274         LASSERT(d);
275
276         if (unlikely(atomic_read(&d->opd_sync_barrier) > 0))
277                 return 0;
278         if (unlikely(osp_sync_in_flight_conflict(d, rec)))
279                 return 0;
280         if (!osp_sync_rpcs_in_progress_low(d))
281                 return 0;
282         if (!osp_sync_rpcs_in_flight_low(d))
283                 return 0;
284         if (!d->opd_imp_connected)
285                 return 0;
286         if (d->opd_sync_prev_done == 0)
287                 return 1;
288         if (atomic_read(&d->opd_sync_changes) == 0)
289                 return 0;
290         if (rec == NULL)
291                 return 1;
292         /* notice "<" not "<=" */
293         if (osp_sync_correct_id(d, rec) < d->opd_sync_last_committed_id)
294                 return 1;
295         return 0;
296 }
297
298 /**
299  * Declare intention to add a new change.
300  *
301  * With regard to OSD API, we have to declare any changes ahead. In this
302  * case we declare an intention to add a llog record representing the
303  * change on the local storage.
304  *
305  * \param[in] env       LU environment provided by the caller
306  * \param[in] o         OSP object
307  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
308  * \param[in] th        transaction handle (local)
309  *
310  * \retval 0            on success
311  * \retval negative     negated errno on error
312  */
313 int osp_sync_declare_add(const struct lu_env *env, struct osp_object *o,
314                          llog_op_type type, struct thandle *th)
315 {
316         struct osp_thread_info  *osi = osp_env_info(env);
317         struct osp_device       *d = lu2osp_dev(o->opo_obj.do_lu.lo_dev);
318         struct llog_ctxt        *ctxt;
319         struct thandle          *storage_th;
320         int                      rc;
321
322         ENTRY;
323
324         /* it's a layering violation, to access internals of th,
325          * but we can do this as a sanity check, for a while */
326         LASSERT(th->th_top != NULL);
327         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
328         if (IS_ERR(storage_th))
329                 RETURN(PTR_ERR(storage_th));
330
331         switch (type) {
332         case MDS_UNLINK64_REC:
333                 osi->osi_hdr.lrh_len = sizeof(struct llog_unlink64_rec);
334                 break;
335         case MDS_SETATTR64_REC:
336                 osi->osi_hdr.lrh_len = sizeof(struct llog_setattr64_rec_v2);
337                 break;
338         default:
339                 LBUG();
340         }
341
342         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
343         LASSERT(ctxt);
344
345         rc = llog_declare_add(env, ctxt->loc_handle, &osi->osi_hdr,
346                               storage_th);
347         llog_ctxt_put(ctxt);
348
349         RETURN(rc);
350 }
351
352 /* add the commit callback every second */
353 int osp_sync_add_commit_cb_1s(const struct lu_env *env, struct osp_device *d,
354                               struct thandle *th)
355 {
356         int add = 0;
357
358         /* fast path */
359         if (cfs_time_before(cfs_time_current(), d->opd_sync_next_commit_cb))
360                 return 0;
361
362         spin_lock(&d->opd_sync_lock);
363         if (cfs_time_aftereq(cfs_time_current(), d->opd_sync_next_commit_cb))
364                 add = 1;
365         d->opd_sync_next_commit_cb = cfs_time_shift(1);
366         spin_unlock(&d->opd_sync_lock);
367
368         if (add == 0)
369                 return 0;
370         return osp_sync_add_commit_cb(env, d, th);
371 }
372
373
374 /**
375  * Generate a llog record for a given change.
376  *
377  * Generates a llog record for the change passed. The change can be of two
378  * types: unlink and setattr. The record gets an ID which later will be
379  * used to track commit status of the change. For unlink changes, the caller
380  * can supply a starting FID and the count of the objects to destroy. For
381  * setattr the caller should apply attributes to apply.
382  *
383  *
384  * \param[in] env       LU environment provided by the caller
385  * \param[in] d         OSP device
386  * \param[in] fid       fid of the object the change should be applied to
387  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
388  * \param[in] count     count of objects to destroy
389  * \param[in] th        transaction handle (local)
390  * \param[in] attr      attributes for setattr
391  *
392  * \retval 0            on success
393  * \retval negative     negated errno on error
394  */
395 static int osp_sync_add_rec(const struct lu_env *env, struct osp_device *d,
396                             const struct lu_fid *fid, llog_op_type type,
397                             int count, struct thandle *th,
398                             const struct lu_attr *attr)
399 {
400         struct osp_thread_info  *osi = osp_env_info(env);
401         struct llog_ctxt        *ctxt;
402         struct thandle          *storage_th;
403         int                      rc;
404
405         ENTRY;
406
407         /* it's a layering violation, to access internals of th,
408          * but we can do this as a sanity check, for a while */
409         LASSERT(th->th_top != NULL);
410         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
411         if (IS_ERR(storage_th))
412                 RETURN(PTR_ERR(storage_th));
413
414         switch (type) {
415         case MDS_UNLINK64_REC:
416                 osi->osi_hdr.lrh_len = sizeof(osi->osi_unlink);
417                 osi->osi_hdr.lrh_type = MDS_UNLINK64_REC;
418                 osi->osi_unlink.lur_fid  = *fid;
419                 osi->osi_unlink.lur_count = count;
420                 break;
421         case MDS_SETATTR64_REC:
422                 rc = fid_to_ostid(fid, &osi->osi_oi);
423                 LASSERT(rc == 0);
424                 osi->osi_hdr.lrh_len = sizeof(osi->osi_setattr);
425                 osi->osi_hdr.lrh_type = MDS_SETATTR64_REC;
426                 osi->osi_setattr.lsr_oi  = osi->osi_oi;
427                 LASSERT(attr);
428                 osi->osi_setattr.lsr_uid = attr->la_uid;
429                 osi->osi_setattr.lsr_gid = attr->la_gid;
430                 osi->osi_setattr.lsr_layout_version = attr->la_layout_version;
431                 osi->osi_setattr.lsr_projid = attr->la_projid;
432                 osi->osi_setattr.lsr_valid =
433                         ((attr->la_valid & LA_UID) ? OBD_MD_FLUID : 0) |
434                         ((attr->la_valid & LA_GID) ? OBD_MD_FLGID : 0) |
435                         ((attr->la_valid & LA_PROJID) ? OBD_MD_FLPROJID : 0);
436                 if (attr->la_valid & LA_LAYOUT_VERSION)
437                         osi->osi_setattr.lsr_valid |= OBD_MD_LAYOUT_VERSION;
438                 break;
439         default:
440                 LBUG();
441         }
442
443         /* we keep the same id, but increment it when the callback
444          * is registered, so that all records upto the one taken
445          * by the callback are subject to processing */
446         spin_lock(&d->opd_sync_lock);
447         osi->osi_hdr.lrh_id = d->opd_sync_last_used_id;
448         spin_unlock(&d->opd_sync_lock);
449
450         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
451         if (ctxt == NULL)
452                 RETURN(-ENOMEM);
453
454         rc = llog_add(env, ctxt->loc_handle, &osi->osi_hdr, &osi->osi_cookie,
455                       storage_th);
456         llog_ctxt_put(ctxt);
457
458         if (likely(rc >= 0)) {
459                 CDEBUG(D_OTHER, "%s: new record "DFID":%x.%u: rc = %d\n",
460                        d->opd_obd->obd_name,
461                        PFID(&osi->osi_cookie.lgc_lgl.lgl_oi.oi_fid),
462                        osi->osi_cookie.lgc_lgl.lgl_ogen,
463                        osi->osi_cookie.lgc_index, rc);
464                 atomic_inc(&d->opd_sync_changes);
465         }
466
467         rc = osp_sync_add_commit_cb_1s(env, d, th);
468
469         /* return 0 always here, error case just cause no llog record */
470         RETURN(0);
471 }
472
473 int osp_sync_add(const struct lu_env *env, struct osp_object *o,
474                  llog_op_type type, struct thandle *th,
475                  const struct lu_attr *attr)
476 {
477         return osp_sync_add_rec(env, lu2osp_dev(o->opo_obj.do_lu.lo_dev),
478                                 lu_object_fid(&o->opo_obj.do_lu), type, 1,
479                                 th, attr);
480 }
481
482 int osp_sync_gap(const struct lu_env *env, struct osp_device *d,
483                         struct lu_fid *fid, int lost, struct thandle *th)
484 {
485         return osp_sync_add_rec(env, d, fid, MDS_UNLINK64_REC, lost, th, NULL);
486 }
487
488 /*
489  * it's quite obvious we can't maintain all the structures in the memory:
490  * while OST is down, MDS can be processing thousands and thousands of unlinks
491  * filling persistent llogs and in-core respresentation
492  *
493  * this doesn't scale at all. so we need basically the following:
494  * a) destroy/setattr append llog records
495  * b) once llog has grown to X records, we process first Y committed records
496  *
497  *  once record R is found via llog_process(), it becomes committed after any
498  *  subsequent commit callback (at the most)
499  */
500
501 /**
502  * ptlrpc commit callback.
503  *
504  * The callback is called by PTLRPC when a RPC is reported committed by the
505  * target (OST). We register the callback for the every RPC applying a change
506  * from the llog. This way we know then the llog records can be cancelled.
507  * Notice the callback can be called when OSP is finishing. We can detect this
508  * checking that actual transno in the request is less or equal of known
509  * committed transno (see osp_sync_process_committed() for the details).
510  * XXX: this is pretty expensive and can be improved later using batching.
511  *
512  * \param[in] req       request
513  */
514 static void osp_sync_request_commit_cb(struct ptlrpc_request *req)
515 {
516         struct osp_device *d = req->rq_cb_data;
517         struct osp_job_req_args *jra;
518
519         CDEBUG(D_HA, "commit req %p, transno %llu\n", req, req->rq_transno);
520
521         if (unlikely(req->rq_transno == 0))
522                 return;
523
524         /* do not do any opd_sync_rpcs_* accounting here
525          * it's done in osp_sync_interpret sooner or later */
526         LASSERT(d);
527
528         jra = ptlrpc_req_async_args(req);
529         LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
530         LASSERT(list_empty(&jra->jra_committed_link));
531
532         ptlrpc_request_addref(req);
533
534         spin_lock(&d->opd_sync_lock);
535         list_add(&jra->jra_committed_link, &d->opd_sync_committed_there);
536         spin_unlock(&d->opd_sync_lock);
537
538         /* XXX: some batching wouldn't hurt */
539         wake_up(&d->opd_sync_waitq);
540 }
541
542 /**
543  * RPC interpretation callback.
544  *
545  * The callback is called by ptlrpc when RPC is replied. Now we have to decide
546  * whether we should:
547  *  - put request on a special list to wait until it's committed by the target,
548  *    if the request is successful
549  *  - schedule llog record cancel if no target object is found
550  *  - try later (essentially after reboot) in case of unexpected error
551  *
552  * \param[in] env       LU environment provided by the caller
553  * \param[in] req       request replied
554  * \param[in] aa        callback data
555  * \param[in] rc        result of RPC
556  *
557  * \retval 0            always
558  */
559 static int osp_sync_interpret(const struct lu_env *env,
560                               struct ptlrpc_request *req, void *aa, int rc)
561 {
562         struct osp_device *d = req->rq_cb_data;
563         struct osp_job_req_args *jra = aa;
564
565         if (jra->jra_magic != OSP_JOB_MAGIC) {
566                 DEBUG_REQ(D_ERROR, req, "bad magic %u\n", jra->jra_magic);
567                 LBUG();
568         }
569         LASSERT(d);
570
571         CDEBUG(D_HA, "reply req %p/%d, rc %d, transno %u\n", req,
572                atomic_read(&req->rq_refcount),
573                rc, (unsigned) req->rq_transno);
574         LASSERT(rc || req->rq_transno);
575
576         if (rc == -ENOENT) {
577                 /*
578                  * we tried to destroy object or update attributes,
579                  * but object doesn't exist anymore - cancell llog record
580                  */
581                 LASSERT(req->rq_transno == 0);
582                 LASSERT(list_empty(&jra->jra_committed_link));
583
584                 ptlrpc_request_addref(req);
585
586                 spin_lock(&d->opd_sync_lock);
587                 list_add(&jra->jra_committed_link,
588                          &d->opd_sync_committed_there);
589                 spin_unlock(&d->opd_sync_lock);
590
591                 wake_up(&d->opd_sync_waitq);
592         } else if (rc) {
593                 struct obd_import *imp = req->rq_import;
594                 /*
595                  * error happened, we'll try to repeat on next boot ?
596                  */
597                 LASSERTF(req->rq_transno == 0 ||
598                          req->rq_import_generation < imp->imp_generation,
599                          "transno %llu, rc %d, gen: req %d, imp %d\n",
600                          req->rq_transno, rc, req->rq_import_generation,
601                          imp->imp_generation);
602                 if (req->rq_transno == 0) {
603                         /* this is the last time we see the request
604                          * if transno is not zero, then commit cb
605                          * will be called at some point */
606                         LASSERT(atomic_read(&d->opd_sync_rpcs_in_progress) > 0);
607                         atomic_dec(&d->opd_sync_rpcs_in_progress);
608                 }
609
610                 wake_up(&d->opd_sync_waitq);
611         } else if (d->opd_pre != NULL &&
612                    unlikely(d->opd_pre_status == -ENOSPC)) {
613                 /*
614                  * if current status is -ENOSPC (lack of free space on OST)
615                  * then we should poll OST immediately once object destroy
616                  * is replied
617                  */
618                 osp_statfs_need_now(d);
619         }
620
621         spin_lock(&d->opd_sync_lock);
622         list_del_init(&jra->jra_in_flight_link);
623         spin_unlock(&d->opd_sync_lock);
624         LASSERT(atomic_read(&d->opd_sync_rpcs_in_flight) > 0);
625         atomic_dec(&d->opd_sync_rpcs_in_flight);
626         if (unlikely(atomic_read(&d->opd_sync_barrier) > 0))
627                 wake_up(&d->opd_sync_barrier_waitq);
628         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
629                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
630                atomic_read(&d->opd_sync_rpcs_in_progress));
631
632         osp_sync_check_for_work(d);
633
634         return 0;
635 }
636
637 /*
638  ** Add request to ptlrpc queue.
639  *
640  * This is just a tiny helper function to put the request on the sending list
641  *
642  * \param[in] d         OSP device
643  * \param[in] llh       llog handle where the record is stored
644  * \param[in] h         llog record
645  * \param[in] req       request
646  */
647 static void osp_sync_send_new_rpc(struct osp_device *d,
648                                   struct llog_handle *llh,
649                                   struct llog_rec_hdr *h,
650                                   struct ptlrpc_request *req)
651 {
652         struct osp_job_req_args *jra;
653
654         LASSERT(atomic_read(&d->opd_sync_rpcs_in_flight) <=
655                 d->opd_sync_max_rpcs_in_flight);
656
657         jra = ptlrpc_req_async_args(req);
658         jra->jra_magic = OSP_JOB_MAGIC;
659         jra->jra_lcookie.lgc_lgl = llh->lgh_id;
660         jra->jra_lcookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
661         jra->jra_lcookie.lgc_index = h->lrh_index;
662         INIT_LIST_HEAD(&jra->jra_committed_link);
663         spin_lock(&d->opd_sync_lock);
664         list_add_tail(&jra->jra_in_flight_link, &d->opd_sync_in_flight_list);
665         spin_unlock(&d->opd_sync_lock);
666
667         ptlrpcd_add_req(req);
668 }
669
670
671 /**
672  * Allocate and prepare RPC for a new change.
673  *
674  * The function allocates and initializes an RPC which will be sent soon to
675  * apply the change to the target OST. The request is initialized from the
676  * llog record passed. Notice only the fields common to all type of changes
677  * are initialized.
678  *
679  * \param[in] d         OSP device
680  * \param[in] op        type of the change
681  * \param[in] format    request format to be used
682  *
683  * \retval pointer              new request on success
684  * \retval ERR_PTR(errno)       on error
685  */
686 static struct ptlrpc_request *osp_sync_new_job(struct osp_device *d,
687                                                ost_cmd_t op,
688                                                const struct req_format *format)
689 {
690         struct ptlrpc_request   *req;
691         struct obd_import       *imp;
692         int                      rc;
693
694         /* Prepare the request */
695         imp = d->opd_obd->u.cli.cl_import;
696         LASSERT(imp);
697
698         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_ENOMEM))
699                 RETURN(ERR_PTR(-ENOMEM));
700
701         req = ptlrpc_request_alloc(imp, format);
702         if (req == NULL)
703                 RETURN(ERR_PTR(-ENOMEM));
704
705         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, op);
706         if (rc) {
707                 ptlrpc_req_finished(req);
708                 return ERR_PTR(rc);
709         }
710
711         req->rq_interpret_reply = osp_sync_interpret;
712         req->rq_commit_cb = osp_sync_request_commit_cb;
713         req->rq_cb_data = d;
714
715         ptlrpc_request_set_replen(req);
716
717         return req;
718 }
719
720 /**
721  * Generate a request for setattr change.
722  *
723  * The function prepares a new RPC, initializes it with setattr specific
724  * bits and send the RPC.
725  *
726  * \param[in] d         OSP device
727  * \param[in] llh       llog handle where the record is stored
728  * \param[in] h         llog record
729  *
730  * \retval 0            on success
731  * \retval 1            on invalid record
732  * \retval negative     negated errno on error
733  */
734 static int osp_sync_new_setattr_job(struct osp_device *d,
735                                     struct llog_handle *llh,
736                                     struct llog_rec_hdr *h)
737 {
738         struct llog_setattr64_rec       *rec = (struct llog_setattr64_rec *)h;
739         struct ptlrpc_request           *req;
740         struct ost_body                 *body;
741
742         ENTRY;
743         LASSERT(h->lrh_type == MDS_SETATTR64_REC);
744
745         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_INVALID_REC))
746                 RETURN(1);
747
748         /* lsr_valid can only be 0 or HAVE OBD_MD_{FLUID, FLGID, FLPROJID} set,
749          * so no bits other than these should be set. */
750         if ((rec->lsr_valid & ~(OBD_MD_FLUID | OBD_MD_FLGID |
751             OBD_MD_FLPROJID | OBD_MD_LAYOUT_VERSION)) != 0) {
752                 CERROR("%s: invalid setattr record, lsr_valid:%llu\n",
753                         d->opd_obd->obd_name, rec->lsr_valid);
754                 /* return 1 on invalid record */
755                 RETURN(1);
756         }
757
758         req = osp_sync_new_job(d, OST_SETATTR, &RQF_OST_SETATTR);
759         if (IS_ERR(req))
760                 RETURN(PTR_ERR(req));
761
762         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
763         LASSERT(body);
764         body->oa.o_oi = rec->lsr_oi;
765         body->oa.o_uid = rec->lsr_uid;
766         body->oa.o_gid = rec->lsr_gid;
767         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
768         if (h->lrh_len > sizeof(struct llog_setattr64_rec)) {
769                 struct llog_setattr64_rec_v2 *rec_v2 = (typeof(rec_v2))rec;
770                 body->oa.o_projid = rec_v2->lsr_projid;
771                 body->oa.o_layout_version = rec_v2->lsr_layout_version;
772         }
773
774         /* old setattr record (prior 2.6.0) doesn't have 'valid' stored,
775          * we assume that both UID and GID are valid in that case. */
776         if (rec->lsr_valid == 0)
777                 body->oa.o_valid |= (OBD_MD_FLUID | OBD_MD_FLGID);
778         else
779                 body->oa.o_valid |= rec->lsr_valid;
780
781         if (body->oa.o_valid & OBD_MD_LAYOUT_VERSION) {
782                 OBD_FAIL_TIMEOUT(OBD_FAIL_FLR_LV_DELAY, cfs_fail_val);
783                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_FLR_LV_INC)))
784                         ++body->oa.o_layout_version;
785         }
786
787         osp_sync_send_new_rpc(d, llh, h, req);
788         RETURN(0);
789 }
790
791 /**
792  * Generate a request for unlink change.
793  *
794  * The function prepares a new RPC, initializes it with unlink(destroy)
795  * specific bits and sends the RPC. The function is used to handle
796  * llog_unlink_rec which were used in the older versions of Lustre.
797  * Current version uses llog_unlink_rec64.
798  *
799  * \param[in] d         OSP device
800  * \param[in] llh       llog handle where the record is stored
801  * \param[in] h         llog record
802  *
803  * \retval 0            on success
804  * \retval negative     negated errno on error
805  */
806 static int osp_sync_new_unlink_job(struct osp_device *d,
807                                    struct llog_handle *llh,
808                                    struct llog_rec_hdr *h)
809 {
810         struct llog_unlink_rec  *rec = (struct llog_unlink_rec *)h;
811         struct ptlrpc_request   *req;
812         struct ost_body         *body;
813         int rc;
814
815         ENTRY;
816         LASSERT(h->lrh_type == MDS_UNLINK_REC);
817
818         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
819         if (IS_ERR(req))
820                 RETURN(PTR_ERR(req));
821
822         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
823         LASSERT(body);
824         ostid_set_seq(&body->oa.o_oi, rec->lur_oseq);
825         rc = ostid_set_id(&body->oa.o_oi, rec->lur_oid);
826         if (rc)
827                 return rc;
828         body->oa.o_misc = rec->lur_count;
829         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
830         if (rec->lur_count)
831                 body->oa.o_valid |= OBD_MD_FLOBJCOUNT;
832
833         osp_sync_send_new_rpc(d, llh, h, req);
834         RETURN(0);
835 }
836
837 /**
838  * Generate a request for unlink change.
839  *
840  * The function prepares a new RPC, initializes it with unlink(destroy)
841  * specific bits and sends the RPC. Depending on the target (MDT or OST)
842  * two different protocols are used. For MDT we use OUT (basically OSD API
843  * updates transferred via a network). For OST we still use the old
844  * protocol (OBD?), originally for compatibility. Later we can start to
845  * use OUT for OST as well, this will allow batching and better code
846  * unification.
847  *
848  * \param[in] d         OSP device
849  * \param[in] llh       llog handle where the record is stored
850  * \param[in] h         llog record
851  *
852  * \retval 0            on success
853  * \retval negative     negated errno on error
854  */
855 static int osp_sync_new_unlink64_job(struct osp_device *d,
856                                      struct llog_handle *llh,
857                                      struct llog_rec_hdr *h)
858 {
859         struct llog_unlink64_rec        *rec = (struct llog_unlink64_rec *)h;
860         struct ptlrpc_request           *req = NULL;
861         struct ost_body                 *body;
862         int                              rc;
863
864         ENTRY;
865         LASSERT(h->lrh_type == MDS_UNLINK64_REC);
866         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
867         if (IS_ERR(req))
868                 RETURN(PTR_ERR(req));
869
870         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
871         if (body == NULL)
872                 RETURN(-EFAULT);
873         rc = fid_to_ostid(&rec->lur_fid, &body->oa.o_oi);
874         if (rc < 0)
875                 RETURN(rc);
876         body->oa.o_misc = rec->lur_count;
877         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID |
878                            OBD_MD_FLOBJCOUNT;
879         osp_sync_send_new_rpc(d, llh, h, req);
880         RETURN(0);
881 }
882
883 /**
884  * Process llog records.
885  *
886  * This function is called to process the llog records committed locally.
887  * In the recovery model used by OSP we can apply a change to a remote
888  * target once corresponding transaction (like posix unlink) is committed
889  * locally so can't revert.
890  * Depending on the llog record type, a given handler is called that is
891  * responsible for preparing and sending the RPC to apply the change.
892  * Special record type LLOG_GEN_REC marking a reboot is cancelled right away.
893  *
894  * \param[in] env       LU environment provided by the caller
895  * \param[in] d         OSP device
896  * \param[in] llh       llog handle where the record is stored
897  * \param[in] rec       llog record
898  */
899 static void osp_sync_process_record(const struct lu_env *env,
900                                     struct osp_device *d,
901                                     struct llog_handle *llh,
902                                     struct llog_rec_hdr *rec)
903 {
904         struct llog_handle      *cathandle = llh->u.phd.phd_cat_handle;
905         struct llog_cookie       cookie;
906         int                      rc = 0;
907
908         ENTRY;
909
910         cookie.lgc_lgl = llh->lgh_id;
911         cookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
912         cookie.lgc_index = rec->lrh_index;
913
914         d->opd_sync_last_catalog_idx = llh->lgh_hdr->llh_cat_idx;
915
916         if (unlikely(rec->lrh_type == LLOG_GEN_REC)) {
917                 struct llog_gen_rec *gen = (struct llog_gen_rec *)rec;
918
919                 /* we're waiting for the record generated by this instance */
920                 LASSERT(d->opd_sync_prev_done == 0);
921                 if (!memcmp(&d->opd_sync_generation, &gen->lgr_gen,
922                             sizeof(gen->lgr_gen))) {
923                         CDEBUG(D_HA, "processed all old entries\n");
924                         d->opd_sync_prev_done = 1;
925                 }
926
927                 /* cancel any generation record */
928                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
929
930                 RETURN_EXIT;
931         }
932
933         /*
934          * now we prepare and fill requests to OST, put them on the queue
935          * and fire after next commit callback
936          */
937
938         /* notice we increment counters before sending RPC, to be consistent
939          * in RPC interpret callback which may happen very quickly */
940         atomic_inc(&d->opd_sync_rpcs_in_flight);
941         atomic_inc(&d->opd_sync_rpcs_in_progress);
942
943         switch (rec->lrh_type) {
944         /* case MDS_UNLINK_REC is kept for compatibility */
945         case MDS_UNLINK_REC:
946                 rc = osp_sync_new_unlink_job(d, llh, rec);
947                 break;
948         case MDS_UNLINK64_REC:
949                 rc = osp_sync_new_unlink64_job(d, llh, rec);
950                 break;
951         case MDS_SETATTR64_REC:
952                 rc = osp_sync_new_setattr_job(d, llh, rec);
953                 break;
954         default:
955                 CERROR("%s: unknown record type: %x\n", d->opd_obd->obd_name,
956                        rec->lrh_type);
957                 /* treat "unknown record type" as "invalid" */
958                 rc = 1;
959                 break;
960         }
961
962         /* For all kinds of records, not matter successful or not,
963          * we should decrease changes and bump last_processed_id.
964          */
965         if (d->opd_sync_prev_done) {
966                 LASSERT(atomic_read(&d->opd_sync_changes) > 0);
967                 atomic_dec(&d->opd_sync_changes);
968                 wake_up(&d->opd_sync_barrier_waitq);
969         }
970         atomic64_inc(&d->opd_sync_processed_recs);
971         if (rc != 0) {
972                 atomic_dec(&d->opd_sync_rpcs_in_flight);
973                 atomic_dec(&d->opd_sync_rpcs_in_progress);
974         }
975
976         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
977                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
978                atomic_read(&d->opd_sync_rpcs_in_progress));
979
980         /* Delete the invalid record */
981         if (rc == 1) {
982                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
983                 if (rc != 0)
984                         CERROR("%s: can't delete invalid record: "
985                                "fid = "DFID", rec_id = %u, rc = %d\n",
986                                d->opd_obd->obd_name,
987                                PFID(lu_object_fid(&cathandle->lgh_obj->do_lu)),
988                                rec->lrh_id, rc);
989         }
990
991         CDEBUG(D_HA, "found record %x, %d, idx %u, id %u\n",
992                rec->lrh_type, rec->lrh_len, rec->lrh_index, rec->lrh_id);
993
994         RETURN_EXIT;
995 }
996
997 /**
998  * Cancel llog records for the committed changes.
999  *
1000  * The function walks through the list of the committed RPCs and cancels
1001  * corresponding llog records. see osp_sync_request_commit_cb() for the
1002  * details.
1003  *
1004  * \param[in] env       LU environment provided by the caller
1005  * \param[in] d         OSP device
1006  */
1007 static void osp_sync_process_committed(const struct lu_env *env,
1008                                        struct osp_device *d)
1009 {
1010         struct obd_device       *obd = d->opd_obd;
1011         struct obd_import       *imp = obd->u.cli.cl_import;
1012         struct ost_body         *body;
1013         struct ptlrpc_request   *req;
1014         struct llog_ctxt        *ctxt;
1015         struct llog_handle      *llh;
1016         struct list_head         list;
1017         int                      rc, done = 0;
1018
1019         ENTRY;
1020
1021         if (list_empty(&d->opd_sync_committed_there))
1022                 return;
1023
1024         /*
1025          * if current status is -ENOSPC (lack of free space on OST)
1026          * then we should poll OST immediately once object destroy
1027          * is committed.
1028          * notice: we do this upon commit as well because some backends
1029          * (like DMU) do not release space right away.
1030          */
1031         if (d->opd_pre != NULL && unlikely(d->opd_pre_status == -ENOSPC))
1032                 osp_statfs_need_now(d);
1033
1034         /*
1035          * now cancel them all
1036          * XXX: can we improve this using some batching?
1037          *      with batch RPC that'll happen automatically?
1038          * XXX: can we store ctxt in lod_device and save few cycles ?
1039          */
1040         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1041         LASSERT(ctxt);
1042
1043         llh = ctxt->loc_handle;
1044         LASSERT(llh);
1045
1046         INIT_LIST_HEAD(&list);
1047         spin_lock(&d->opd_sync_lock);
1048         list_splice(&d->opd_sync_committed_there, &list);
1049         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1050         spin_unlock(&d->opd_sync_lock);
1051
1052         while (!list_empty(&list)) {
1053                 struct osp_job_req_args *jra;
1054
1055                 jra = list_entry(list.next, struct osp_job_req_args,
1056                                  jra_committed_link);
1057                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
1058                 list_del_init(&jra->jra_committed_link);
1059
1060                 req = container_of((void *)jra, struct ptlrpc_request,
1061                                    rq_async_args);
1062                 body = req_capsule_client_get(&req->rq_pill,
1063                                               &RMF_OST_BODY);
1064                 LASSERT(body);
1065                 /* import can be closing, thus all commit cb's are
1066                  * called we can check committness directly */
1067                 if (req->rq_import_generation == imp->imp_generation) {
1068                         rc = llog_cat_cancel_records(env, llh, 1,
1069                                                      &jra->jra_lcookie);
1070                         if (rc)
1071                                 CERROR("%s: can't cancel record: %d\n",
1072                                        obd->obd_name, rc);
1073                 } else {
1074                         DEBUG_REQ(D_OTHER, req, "imp_committed = %llu",
1075                                   imp->imp_peer_committed_transno);
1076                 }
1077                 ptlrpc_req_finished(req);
1078                 done++;
1079         }
1080
1081         llog_ctxt_put(ctxt);
1082
1083         LASSERT(atomic_read(&d->opd_sync_rpcs_in_progress) >= done);
1084         atomic_sub(done, &d->opd_sync_rpcs_in_progress);
1085         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
1086                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
1087                atomic_read(&d->opd_sync_rpcs_in_progress));
1088
1089         osp_sync_check_for_work(d);
1090
1091         /* wake up the thread if requested to stop:
1092          * it might be waiting for in-progress to complete */
1093         if (unlikely(osp_sync_running(d) == 0))
1094                 wake_up(&d->opd_sync_waitq);
1095
1096         EXIT;
1097 }
1098
1099 /**
1100  * The core of the syncing mechanism.
1101  *
1102  * This is a callback called by the llog processing function. Essentially it
1103  * suspends llog processing until there is a record to process (it's supposed
1104  * to be committed locally). The function handles RPCs committed by the target
1105  * and cancels corresponding llog records.
1106  *
1107  * \param[in] env       LU environment provided by the caller
1108  * \param[in] llh       llog handle we're processing
1109  * \param[in] rec       current llog record
1110  * \param[in] data      callback data containing a pointer to the device
1111  *
1112  * \retval 0                    to ask the caller (llog_process()) to continue
1113  * \retval LLOG_PROC_BREAK      to ask the caller to break
1114  */
1115 static int osp_sync_process_queues(const struct lu_env *env,
1116                                    struct llog_handle *llh,
1117                                    struct llog_rec_hdr *rec,
1118                                    void *data)
1119 {
1120         struct osp_device       *d = data;
1121
1122         do {
1123                 struct l_wait_info lwi = { 0 };
1124
1125                 if (!osp_sync_running(d)) {
1126                         CDEBUG(D_HA, "stop llog processing\n");
1127                         return LLOG_PROC_BREAK;
1128                 }
1129
1130                 /* process requests committed by OST */
1131                 osp_sync_process_committed(env, d);
1132
1133                 /* if we there are changes to be processed and we have
1134                  * resources for this ... do now */
1135                 if (osp_sync_can_process_new(d, rec)) {
1136                         if (llh == NULL) {
1137                                 /* ask llog for another record */
1138                                 CDEBUG(D_HA, "%u changes, %u in progress,"
1139                                      " %u in flight\n",
1140                                      atomic_read(&d->opd_sync_changes),
1141                                      atomic_read(&d->opd_sync_rpcs_in_progress),
1142                                      atomic_read(&d->opd_sync_rpcs_in_flight));
1143                                 return 0;
1144                         }
1145                         osp_sync_process_record(env, d, llh, rec);
1146                         llh = NULL;
1147                         rec = NULL;
1148                 }
1149
1150                 l_wait_event(d->opd_sync_waitq,
1151                              !osp_sync_running(d) ||
1152                              osp_sync_can_process_new(d, rec) ||
1153                              !list_empty(&d->opd_sync_committed_there),
1154                              &lwi);
1155         } while (1);
1156 }
1157
1158 /**
1159  * OSP sync thread.
1160  *
1161  * This thread runs llog_cat_process() scanner calling our callback
1162  * to process llog records. in the callback we implement tricky
1163  * state machine as we don't want to start scanning of the llog again
1164  * and again, also we don't want to process too many records and send
1165  * too many RPCs a time. so, depending on current load (num of changes
1166  * being synced to OST) the callback can suspend awaiting for some
1167  * new conditions, like syncs completed.
1168  *
1169  * In order to process llog records left by previous boots and to allow
1170  * llog_process_thread() to find something (otherwise it'd just exit
1171  * immediately) we add a special GENERATATION record on each boot.
1172  *
1173  * \param[in] _arg      a pointer to thread's arguments
1174  *
1175  * \retval 0            on success
1176  * \retval negative     negated errno on error
1177  */
1178 static int osp_sync_thread(void *_arg)
1179 {
1180         struct osp_device       *d = _arg;
1181         struct ptlrpc_thread    *thread = &d->opd_sync_thread;
1182         struct l_wait_info       lwi = { 0 };
1183         struct llog_ctxt        *ctxt;
1184         struct obd_device       *obd = d->opd_obd;
1185         struct llog_handle      *llh;
1186         struct lu_env            env;
1187         int                      rc, count;
1188         bool                     wrapped;
1189
1190         ENTRY;
1191
1192         rc = lu_env_init(&env, LCT_LOCAL);
1193         if (rc) {
1194                 CERROR("%s: can't initialize env: rc = %d\n",
1195                        obd->obd_name, rc);
1196
1197                 spin_lock(&d->opd_sync_lock);
1198                 thread->t_flags = SVC_STOPPED;
1199                 spin_unlock(&d->opd_sync_lock);
1200                 wake_up(&thread->t_ctl_waitq);
1201
1202                 RETURN(rc);
1203         }
1204
1205         spin_lock(&d->opd_sync_lock);
1206         thread->t_flags = SVC_RUNNING;
1207         spin_unlock(&d->opd_sync_lock);
1208         wake_up(&thread->t_ctl_waitq);
1209
1210         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1211         if (ctxt == NULL) {
1212                 CERROR("can't get appropriate context\n");
1213                 GOTO(out, rc = -EINVAL);
1214         }
1215
1216         llh = ctxt->loc_handle;
1217         if (llh == NULL) {
1218                 CERROR("can't get llh\n");
1219                 llog_ctxt_put(ctxt);
1220                 GOTO(out, rc = -EINVAL);
1221         }
1222
1223         /*
1224          * Catalog processing stops when it processed last catalog record
1225          * with index equal to the end of catalog bitmap. Or if it is wrapped,
1226          * processing stops with index equal to the lgh_last_idx. We need to
1227          * continue processing.
1228          */
1229         d->opd_sync_last_catalog_idx = 0;
1230         do {
1231                 int     size;
1232
1233                 wrapped = (llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
1234                            llh->lgh_hdr->llh_count > 1);
1235
1236                 rc = llog_cat_process(&env, llh, osp_sync_process_queues, d,
1237                                       d->opd_sync_last_catalog_idx, 0);
1238
1239                 size = OBD_FAIL_PRECHECK(OBD_FAIL_CAT_RECORDS) ?
1240                        cfs_fail_val : (LLOG_HDR_BITMAP_SIZE(llh->lgh_hdr) - 1);
1241                 /* processing reaches catalog bottom */
1242                 if (d->opd_sync_last_catalog_idx == size)
1243                         d->opd_sync_last_catalog_idx = 0;
1244                 else if (wrapped)
1245                         /* If catalog is wrapped we can`t predict last index of
1246                          * processing because lgh_last_idx could be changed.
1247                          * Starting form the next one */
1248                         d->opd_sync_last_catalog_idx++;
1249
1250         } while (rc == 0 && (wrapped || d->opd_sync_last_catalog_idx == 0));
1251
1252         if (rc < 0) {
1253                 CERROR("%s: llog process with osp_sync_process_queues "
1254                        "failed: %d\n", d->opd_obd->obd_name, rc);
1255                 GOTO(close, rc);
1256         }
1257         LASSERTF(rc == 0 || rc == LLOG_PROC_BREAK,
1258                  "%u changes, %u in progress, %u in flight: %d\n",
1259                  atomic_read(&d->opd_sync_changes),
1260                  atomic_read(&d->opd_sync_rpcs_in_progress),
1261                  atomic_read(&d->opd_sync_rpcs_in_flight), rc);
1262
1263         /* we don't expect llog_process_thread() to exit till umount */
1264         LASSERTF(thread->t_flags != SVC_RUNNING,
1265                  "%u changes, %u in progress, %u in flight\n",
1266                  atomic_read(&d->opd_sync_changes),
1267                  atomic_read(&d->opd_sync_rpcs_in_progress),
1268                  atomic_read(&d->opd_sync_rpcs_in_flight));
1269
1270         /* wait till all the requests are completed */
1271         count = 0;
1272         while (atomic_read(&d->opd_sync_rpcs_in_progress) > 0) {
1273                 osp_sync_process_committed(&env, d);
1274
1275                 lwi = LWI_TIMEOUT(cfs_time_seconds(5), NULL, NULL);
1276                 rc = l_wait_event(d->opd_sync_waitq,
1277                                 atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1278                                   &lwi);
1279                 if (rc == -ETIMEDOUT)
1280                         count++;
1281                 LASSERTF(count < 10, "%s: %d %d %sempty\n",
1282                          d->opd_obd->obd_name,
1283                          atomic_read(&d->opd_sync_rpcs_in_progress),
1284                          atomic_read(&d->opd_sync_rpcs_in_flight),
1285                          list_empty(&d->opd_sync_committed_there) ? "" : "!");
1286
1287         }
1288
1289 close:
1290         llog_cat_close(&env, llh);
1291         rc = llog_cleanup(&env, ctxt);
1292         if (rc)
1293                 CERROR("can't cleanup llog: %d\n", rc);
1294 out:
1295         LASSERTF(atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1296                  "%s: %d %d %sempty\n", d->opd_obd->obd_name,
1297                  atomic_read(&d->opd_sync_rpcs_in_progress),
1298                  atomic_read(&d->opd_sync_rpcs_in_flight),
1299                  list_empty(&d->opd_sync_committed_there) ? "" : "!");
1300
1301         thread->t_flags = SVC_STOPPED;
1302
1303         wake_up(&thread->t_ctl_waitq);
1304
1305         lu_env_fini(&env);
1306
1307         RETURN(0);
1308 }
1309
1310 /**
1311  * Initialize llog.
1312  *
1313  * Initializes the llog. Specific llog to be used depends on the type of the
1314  * target OSP represents (OST or MDT). The function adds appends a new llog
1315  * record to mark the place where the records associated with this boot
1316  * start.
1317  *
1318  * \param[in] env       LU environment provided by the caller
1319  * \param[in] d         OSP device
1320  *
1321  * \retval 0            on success
1322  * \retval negative     negated errno on error
1323  */
1324 static int osp_sync_llog_init(const struct lu_env *env, struct osp_device *d)
1325 {
1326         struct osp_thread_info  *osi = osp_env_info(env);
1327         struct lu_fid           *fid = &osi->osi_fid;
1328         struct llog_handle      *lgh = NULL;
1329         struct obd_device       *obd = d->opd_obd;
1330         struct llog_ctxt        *ctxt;
1331         int                     rc;
1332
1333         ENTRY;
1334
1335         LASSERT(obd);
1336
1337         /*
1338          * open llog corresponding to our OST
1339          */
1340         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1341         obd->obd_lvfs_ctxt.dt = d->opd_storage;
1342
1343         lu_local_obj_fid(fid, LLOG_CATALOGS_OID);
1344
1345         rc = llog_osd_get_cat_list(env, d->opd_storage, d->opd_index, 1,
1346                                    &osi->osi_cid, fid);
1347         if (rc < 0) {
1348                 if (rc != -EFAULT) {
1349                         CERROR("%s: can't get id from catalogs: rc = %d\n",
1350                                obd->obd_name, rc);
1351                         RETURN(rc);
1352                 }
1353
1354                 /* After sparse OST indices is supported, the CATALOG file
1355                  * may become a sparse file that results in failure on
1356                  * reading. Skip this error as the llog will be created
1357                  * later */
1358                 memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1359                 rc = 0;
1360         }
1361
1362         CDEBUG(D_INFO, "%s: Init llog for %d - catid "DFID":%x\n",
1363                obd->obd_name, d->opd_index,
1364                PFID(&osi->osi_cid.lci_logid.lgl_oi.oi_fid),
1365                osi->osi_cid.lci_logid.lgl_ogen);
1366
1367         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_MDS_OST_ORIG_CTXT,
1368                         d->opd_storage->dd_lu_dev.ld_obd,
1369                         &osp_mds_ost_orig_logops);
1370         if (rc)
1371                 RETURN(rc);
1372
1373         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1374         LASSERT(ctxt);
1375
1376         if (likely(logid_id(&osi->osi_cid.lci_logid) != 0)) {
1377                 rc = llog_open(env, ctxt, &lgh, &osi->osi_cid.lci_logid, NULL,
1378                                LLOG_OPEN_EXISTS);
1379                 /* re-create llog if it is missing */
1380                 if (rc == -ENOENT)
1381                         logid_set_id(&osi->osi_cid.lci_logid, 0);
1382                 else if (rc < 0)
1383                         GOTO(out_cleanup, rc);
1384         }
1385
1386         if (unlikely(logid_id(&osi->osi_cid.lci_logid) == 0)) {
1387                 rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
1388                 if (rc < 0)
1389                         GOTO(out_cleanup, rc);
1390                 osi->osi_cid.lci_logid = lgh->lgh_id;
1391         }
1392
1393         LASSERT(lgh != NULL);
1394         ctxt->loc_handle = lgh;
1395
1396         rc = llog_init_handle(env, lgh, LLOG_F_IS_CAT, NULL);
1397         if (rc)
1398                 GOTO(out_close, rc);
1399
1400         rc = llog_osd_put_cat_list(env, d->opd_storage, d->opd_index, 1,
1401                                    &osi->osi_cid, fid);
1402         if (rc)
1403                 GOTO(out_close, rc);
1404
1405         /*
1406          * put a mark in the llog till which we'll be processing
1407          * old records restless
1408          */
1409         d->opd_sync_generation.mnt_cnt = cfs_time_current();
1410         d->opd_sync_generation.conn_cnt = cfs_time_current();
1411
1412         osi->osi_hdr.lrh_type = LLOG_GEN_REC;
1413         osi->osi_hdr.lrh_len = sizeof(osi->osi_gen);
1414
1415         memcpy(&osi->osi_gen.lgr_gen, &d->opd_sync_generation,
1416                sizeof(osi->osi_gen.lgr_gen));
1417
1418         rc = llog_cat_add(env, lgh, &osi->osi_gen.lgr_hdr, &osi->osi_cookie);
1419         if (rc < 0)
1420                 GOTO(out_close, rc);
1421         llog_ctxt_put(ctxt);
1422         RETURN(0);
1423 out_close:
1424         llog_cat_close(env, lgh);
1425 out_cleanup:
1426         llog_cleanup(env, ctxt);
1427         RETURN(rc);
1428 }
1429
1430 /**
1431  * Cleanup llog used for syncing.
1432  *
1433  * Closes and cleanups the llog. The function is called when the device is
1434  * shutting down.
1435  *
1436  * \param[in] env       LU environment provided by the caller
1437  * \param[in] d         OSP device
1438  */
1439 static void osp_sync_llog_fini(const struct lu_env *env, struct osp_device *d)
1440 {
1441         struct llog_ctxt *ctxt;
1442
1443         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
1444         if (ctxt) {
1445                 llog_cat_close(env, ctxt->loc_handle);
1446                 llog_cleanup(env, ctxt);
1447         }
1448 }
1449
1450 /**
1451  * Initialization of the sync component of OSP.
1452  *
1453  * Initializes the llog and starts a new thread to handle the changes to
1454  * the remote target (OST or MDT).
1455  *
1456  * \param[in] env       LU environment provided by the caller
1457  * \param[in] d         OSP device
1458  *
1459  * \retval 0            on success
1460  * \retval negative     negated errno on error
1461  */
1462 int osp_sync_init(const struct lu_env *env, struct osp_device *d)
1463 {
1464         struct l_wait_info       lwi = { 0 };
1465         struct task_struct      *task;
1466         int                      rc;
1467
1468         ENTRY;
1469
1470         d->opd_sync_max_rpcs_in_flight = OSP_MAX_RPCS_IN_FLIGHT;
1471         d->opd_sync_max_rpcs_in_progress = OSP_MAX_RPCS_IN_PROGRESS;
1472         spin_lock_init(&d->opd_sync_lock);
1473         init_waitqueue_head(&d->opd_sync_waitq);
1474         init_waitqueue_head(&d->opd_sync_barrier_waitq);
1475         thread_set_flags(&d->opd_sync_thread, SVC_INIT);
1476         init_waitqueue_head(&d->opd_sync_thread.t_ctl_waitq);
1477         INIT_LIST_HEAD(&d->opd_sync_in_flight_list);
1478         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1479
1480         if (d->opd_storage->dd_rdonly)
1481                 RETURN(0);
1482
1483         /*
1484          * initialize llog storing changes
1485          */
1486         rc = osp_sync_llog_init(env, d);
1487         if (rc) {
1488                 CERROR("%s: can't initialize llog: rc = %d\n",
1489                        d->opd_obd->obd_name, rc);
1490                 GOTO(err_id, rc);
1491         }
1492
1493         /*
1494          * Start synchronization thread
1495          */
1496         task = kthread_run(osp_sync_thread, d, "osp-syn-%u-%u",
1497                            d->opd_index, d->opd_group);
1498         if (IS_ERR(task)) {
1499                 rc = PTR_ERR(task);
1500                 CERROR("%s: cannot start sync thread: rc = %d\n",
1501                        d->opd_obd->obd_name, rc);
1502                 GOTO(err_llog, rc);
1503         }
1504
1505         l_wait_event(d->opd_sync_thread.t_ctl_waitq,
1506                      osp_sync_running(d) || osp_sync_stopped(d), &lwi);
1507
1508         RETURN(0);
1509 err_llog:
1510         osp_sync_llog_fini(env, d);
1511 err_id:
1512         return rc;
1513 }
1514
1515 /**
1516  * Stop the syncing thread.
1517  *
1518  * Asks the syncing thread to stop and wait until it's stopped.
1519  *
1520  * \param[in] d         OSP device
1521  *
1522  * \retval              0
1523  */
1524 int osp_sync_fini(struct osp_device *d)
1525 {
1526         struct ptlrpc_thread *thread = &d->opd_sync_thread;
1527
1528         ENTRY;
1529
1530         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1531                 thread->t_flags = SVC_STOPPING;
1532                 wake_up(&d->opd_sync_waitq);
1533                 wait_event(thread->t_ctl_waitq, thread_is_stopped(thread));
1534         }
1535
1536         RETURN(0);
1537 }
1538
1539 struct osp_last_committed_cb {
1540         struct dt_txn_commit_cb  ospc_cb;
1541         struct osp_device       *ospc_dev;
1542         __u64                    ospc_transno;
1543 };
1544
1545 void osp_sync_local_commit_cb(struct lu_env *env, struct thandle *th,
1546                               struct dt_txn_commit_cb *dcb, int err)
1547 {
1548         struct osp_last_committed_cb    *cb;
1549         struct osp_device               *d;
1550
1551         cb = container_of0(dcb, struct osp_last_committed_cb, ospc_cb);
1552         d = cb->ospc_dev;
1553
1554         CDEBUG(D_HA, "%s: %llu committed\n", d->opd_obd->obd_name,
1555                cb->ospc_transno);
1556
1557         spin_lock(&d->opd_sync_lock);
1558         if (cb->ospc_transno > d->opd_sync_last_committed_id)
1559                 d->opd_sync_last_committed_id = cb->ospc_transno;
1560         spin_unlock(&d->opd_sync_lock);
1561
1562         osp_sync_check_for_work(d);
1563         lu_device_put(osp2lu_dev(d));
1564         if (atomic_dec_and_test(&d->opd_commits_registered))
1565                 wake_up(&d->opd_sync_waitq);
1566
1567         OBD_FREE_PTR(cb);
1568 }
1569
1570 int osp_sync_add_commit_cb(const struct lu_env *env, struct osp_device *d,
1571                            struct thandle *th)
1572 {
1573         struct osp_last_committed_cb    *cb;
1574         struct dt_txn_commit_cb         *dcb;
1575         int                              rc = 0;
1576
1577         OBD_ALLOC_PTR(cb);
1578         if (cb == NULL)
1579                 return -ENOMEM;
1580         cb->ospc_dev = d;
1581         dcb = &cb->ospc_cb;
1582         dcb->dcb_func = osp_sync_local_commit_cb;
1583         spin_lock(&d->opd_sync_lock);
1584         cb->ospc_transno = ++d->opd_sync_last_used_id;
1585         spin_unlock(&d->opd_sync_lock);
1586
1587         rc = dt_trans_cb_add(th, dcb);
1588         CDEBUG(D_HA, "%s: add commit cb at %llu, next at %llu, rc = %d\n",
1589                d->opd_obd->obd_name, (unsigned long long) cfs_time_current(),
1590                (unsigned long long) d->opd_sync_next_commit_cb, rc);
1591
1592         if (likely(rc == 0)) {
1593                 lu_device_get(osp2lu_dev(d));
1594                 atomic_inc(&d->opd_commits_registered);
1595         } else
1596                 OBD_FREE_PTR(cb);
1597
1598         return rc;
1599 }
1600
1601 /*
1602  * generate an empty transaction and hook the commit callback in
1603  * then force transaction commit
1604  */
1605 void osp_sync_force(const struct lu_env *env, struct osp_device *d)
1606 {
1607         struct thandle *th;
1608         int rc;
1609
1610         th = dt_trans_create(env, d->opd_storage);
1611         if (IS_ERR(th)) {
1612                 CERROR("%s: can't sync\n", d->opd_obd->obd_name);
1613                 return;
1614         }
1615         rc = dt_trans_start_local(env, d->opd_storage, th);
1616         if (rc == 0) {
1617                 CDEBUG(D_OTHER, "%s: sync forced, %d changes\n",
1618                        d->opd_obd->obd_name,
1619                        atomic_read(&d->opd_sync_changes));
1620                 rc = osp_sync_add_commit_cb(env, d, th);
1621                 dt_trans_stop(env, d->opd_storage, th);
1622         }
1623
1624         dt_commit_async(env, d->opd_storage);
1625 }