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