Whamcloud - gitweb
LU-7117 osp: set ptlrpc_request::rq_allow_replay properly
[fs/lustre-release.git] / lustre / osp / osp_precreate.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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osp/osp_sync.c
37  *
38  * Lustre OST Proxy Device
39  *
40  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
41  * Author: Mikhail Pershin <mike.pershin@intel.com>
42  * Author: Di Wang <di.wang@intel.com>
43  */
44
45 #define DEBUG_SUBSYSTEM S_MDS
46
47 #include <linux/kthread.h>
48
49 #include <lustre_obdo.h>
50
51 #include "osp_internal.h"
52
53 /*
54  * there are two specific states to take care about:
55  *
56  * = import is disconnected =
57  *
58  * = import is inactive =
59  *   in this case osp_declare_object_create() returns an error
60  *
61  */
62
63 /*
64  **
65  * Check whether statfs data is expired
66  *
67  * OSP device caches statfs data for the target, the function checks
68  * whether the data is expired or not.
69  *
70  * \param[in] d         OSP device
71  *
72  * \retval              0 - not expired, 1 - expired
73  */
74 static inline int osp_statfs_need_update(struct osp_device *d)
75 {
76         return !cfs_time_before(cfs_time_current(),
77                                 d->opd_statfs_fresh_till);
78 }
79
80 /*
81  * OSP tries to maintain pool of available objects so that calls to create
82  * objects don't block most of time
83  *
84  * each time OSP gets connected to OST, we should start from precreation cleanup
85  */
86 static inline bool osp_precreate_running(struct osp_device *d)
87 {
88         return !!(d->opd_pre_thread.t_flags & SVC_RUNNING);
89 }
90
91 static inline bool osp_precreate_stopped(struct osp_device *d)
92 {
93         return !!(d->opd_pre_thread.t_flags & SVC_STOPPED);
94 }
95
96 static void osp_statfs_timer_cb(unsigned long _d)
97 {
98         struct osp_device *d = (struct osp_device *) _d;
99
100         LASSERT(d);
101         if (d->opd_pre != NULL && osp_precreate_running(d))
102                 wake_up(&d->opd_pre_waitq);
103 }
104
105 /**
106  * RPC interpret callback for OST_STATFS RPC
107  *
108  * An interpretation callback called by ptlrpc for OST_STATFS RPC when it is
109  * replied by the target. It's used to maintain statfs cache for the target.
110  * The function fills data from the reply if successful and schedules another
111  * update.
112  *
113  * \param[in] env       LU environment provided by the caller
114  * \param[in] req       RPC replied
115  * \param[in] aa        callback data
116  * \param[in] rc        RPC result
117  *
118  * \retval 0            on success
119  * \retval negative     negated errno on error
120  */
121 static int osp_statfs_interpret(const struct lu_env *env,
122                                 struct ptlrpc_request *req,
123                                 union ptlrpc_async_args *aa, int rc)
124 {
125         struct obd_import       *imp = req->rq_import;
126         struct obd_statfs       *msfs;
127         struct osp_device       *d;
128
129         ENTRY;
130
131         aa = ptlrpc_req_async_args(req);
132         d = aa->pointer_arg[0];
133         LASSERT(d);
134
135         if (rc != 0)
136                 GOTO(out, rc);
137
138         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
139         if (msfs == NULL)
140                 GOTO(out, rc = -EPROTO);
141
142         d->opd_statfs = *msfs;
143
144         osp_pre_update_status(d, rc);
145
146         /* schedule next update */
147         d->opd_statfs_fresh_till = cfs_time_shift(d->opd_statfs_maxage);
148         cfs_timer_arm(&d->opd_statfs_timer, d->opd_statfs_fresh_till);
149         d->opd_statfs_update_in_progress = 0;
150
151         CDEBUG(D_CACHE, "updated statfs %p\n", d);
152
153         RETURN(0);
154 out:
155         /* couldn't update statfs, try again as soon as possible */
156         if (d->opd_pre != NULL && osp_precreate_running(d))
157                 wake_up(&d->opd_pre_waitq);
158
159         if (req->rq_import_generation == imp->imp_generation)
160                 CDEBUG(D_CACHE, "%s: couldn't update statfs: rc = %d\n",
161                        d->opd_obd->obd_name, rc);
162         RETURN(rc);
163 }
164
165 /**
166  * Send OST_STATFS RPC
167  *
168  * Sends OST_STATFS RPC to refresh cached statfs data for the target.
169  * Also disables scheduled updates as times OSP may need to refresh
170  * statfs data before expiration. The function doesn't block, instead
171  * an interpretation callback osp_statfs_interpret() is used.
172  *
173  * \param[in] d         OSP device
174  */
175 static int osp_statfs_update(struct osp_device *d)
176 {
177         struct ptlrpc_request   *req;
178         struct obd_import       *imp;
179         union ptlrpc_async_args *aa;
180         int                      rc;
181
182         ENTRY;
183
184         CDEBUG(D_CACHE, "going to update statfs\n");
185
186         imp = d->opd_obd->u.cli.cl_import;
187         LASSERT(imp);
188
189         req = ptlrpc_request_alloc(imp, &RQF_OST_STATFS);
190         if (req == NULL)
191                 RETURN(-ENOMEM);
192
193         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_STATFS);
194         if (rc) {
195                 ptlrpc_request_free(req);
196                 RETURN(rc);
197         }
198         ptlrpc_request_set_replen(req);
199         req->rq_request_portal = OST_CREATE_PORTAL;
200         ptlrpc_at_set_req_timeout(req);
201
202         req->rq_interpret_reply = (ptlrpc_interpterer_t)osp_statfs_interpret;
203         aa = ptlrpc_req_async_args(req);
204         aa->pointer_arg[0] = d;
205
206         /*
207          * no updates till reply
208          */
209         cfs_timer_disarm(&d->opd_statfs_timer);
210         d->opd_statfs_fresh_till = cfs_time_shift(obd_timeout * 1000);
211         d->opd_statfs_update_in_progress = 1;
212
213         ptlrpcd_add_req(req);
214
215         RETURN(0);
216 }
217
218 /**
219  * Schedule an immediate update for statfs data
220  *
221  * If cached statfs data claim no free space, but OSP has got a request to
222  * destroy an object (so release some space probably), then we may need to
223  * refresh cached statfs data sooner than planned. The function checks there
224  * is no statfs update going and schedules immediate update if so.
225  * XXX: there might be a case where removed object(s) do not add free space (empty
226  * object). If the number of such deletions is high, then we can start to update
227  * statfs too often causing a RPC storm. some throttling is needed...
228  *
229  * \param[in] d         OSP device where statfs data needs to be refreshed
230  */
231 void osp_statfs_need_now(struct osp_device *d)
232 {
233         if (!d->opd_statfs_update_in_progress) {
234                 /*
235                  * if current status is -ENOSPC (lack of free space on OST)
236                  * then we should poll OST immediately once object destroy
237                  * is replied
238                  */
239                 d->opd_statfs_fresh_till = cfs_time_shift(-1);
240                 cfs_timer_disarm(&d->opd_statfs_timer);
241                 wake_up(&d->opd_pre_waitq);
242         }
243 }
244
245 /**
246  * Return number of precreated objects
247  *
248  * A simple helper to calculate the number of precreated objects on the device.
249  *
250  * \param[in] env       LU environment provided by the caller
251  * \param[in] osp       OSP device
252  *
253  * \retval              the number of the precreated objects
254  */
255 static inline int osp_objs_precreated(const struct lu_env *env,
256                                       struct osp_device *osp)
257 {
258         return osp_fid_diff(&osp->opd_pre_last_created_fid,
259                             &osp->opd_pre_used_fid);
260 }
261
262 /**
263  * Check pool of precreated objects is nearly empty
264  *
265  * We should not wait till the pool of the precreated objects is exhausted,
266  * because then there will be a long period of OSP being unavailable for the
267  * new creations due to lenghty precreate RPC. Instead we ask for another
268  * precreation ahead and hopefully have it ready before the current pool is
269  * empty. Notice this function relies on an external locking.
270  *
271  * \param[in] env       LU environment provided by the caller
272  * \param[in] d         OSP device
273  *
274  * \retval              0 - current pool is good enough, 1 - time to precreate
275  */
276 static inline int osp_precreate_near_empty_nolock(const struct lu_env *env,
277                                                   struct osp_device *d)
278 {
279         int window = osp_objs_precreated(env, d);
280
281         /* don't consider new precreation till OST is healty and
282          * has free space */
283         return ((window - d->opd_pre_reserved < d->opd_pre_create_count / 2) &&
284                 (d->opd_pre_status == 0));
285 }
286
287 /**
288  * Check pool of precreated objects
289  *
290  * This is protected version of osp_precreate_near_empty_nolock(), check that
291  * for the details.
292  *
293  * \param[in] env       LU environment provided by the caller
294  * \param[in] d         OSP device
295  *
296  * \retval              0 - current pool is good enough, 1 - time to precreate
297  */
298 static inline int osp_precreate_near_empty(const struct lu_env *env,
299                                            struct osp_device *d)
300 {
301         int rc;
302
303         /* XXX: do we really need locking here? */
304         spin_lock(&d->opd_pre_lock);
305         rc = osp_precreate_near_empty_nolock(env, d);
306         spin_unlock(&d->opd_pre_lock);
307         return rc;
308 }
309
310 /**
311  * Check given sequence is empty
312  *
313  * Returns a binary result whether the given sequence has some IDs left
314  * or not. Find the details in osp_fid_end_seq(). This is a lock protected
315  * version of that function.
316  *
317  * \param[in] env       LU environment provided by the caller
318  * \param[in] osp       OSP device
319  *
320  * \retval              0 - current sequence has no IDs, 1 - otherwise
321  */
322 static inline int osp_create_end_seq(const struct lu_env *env,
323                                      struct osp_device *osp)
324 {
325         struct lu_fid *fid = &osp->opd_pre_used_fid;
326         int rc;
327
328         spin_lock(&osp->opd_pre_lock);
329         rc = osp_fid_end_seq(env, fid);
330         spin_unlock(&osp->opd_pre_lock);
331         return rc;
332 }
333
334 /**
335  * Write FID into into last_oid/last_seq file
336  *
337  * The function stores the sequence and the in-sequence id into two dedicated
338  * files. The sync argument can be used to request synchronous commit, so the
339  * function won't return until the updates are committed.
340  *
341  * \param[in] env       LU environment provided by the caller
342  * \param[in] osp       OSP device
343  * \param[in] fid       fid where sequence/id is taken
344  * \param[in] sync      update mode: 0 - asynchronously, 1 - synchronously
345  *
346  * \retval 0            on success
347  * \retval negative     negated errno on error
348  **/
349 int osp_write_last_oid_seq_files(struct lu_env *env, struct osp_device *osp,
350                                  struct lu_fid *fid, int sync)
351 {
352         struct osp_thread_info  *oti = osp_env_info(env);
353         struct lu_buf      *lb_oid = &oti->osi_lb;
354         struct lu_buf      *lb_oseq = &oti->osi_lb2;
355         loff_t             oid_off;
356         loff_t             oseq_off;
357         struct thandle    *th;
358         int                   rc;
359         ENTRY;
360
361         /* Note: through f_oid is only 32 bits, it will also write 64 bits
362          * for oid to keep compatibility with the previous version. */
363         lb_oid->lb_buf = &fid->f_oid;
364         lb_oid->lb_len = sizeof(u64);
365         oid_off = sizeof(u64) * osp->opd_index;
366
367         lb_oseq->lb_buf = &fid->f_seq;
368         lb_oseq->lb_len = sizeof(u64);
369         oseq_off = sizeof(u64) * osp->opd_index;
370
371         th = dt_trans_create(env, osp->opd_storage);
372         if (IS_ERR(th))
373                 RETURN(PTR_ERR(th));
374
375         th->th_sync |= sync;
376         rc = dt_declare_record_write(env, osp->opd_last_used_oid_file,
377                                      lb_oid, oid_off, th);
378         if (rc != 0)
379                 GOTO(out, rc);
380
381         rc = dt_declare_record_write(env, osp->opd_last_used_seq_file,
382                                      lb_oseq, oseq_off, th);
383         if (rc != 0)
384                 GOTO(out, rc);
385
386         rc = dt_trans_start_local(env, osp->opd_storage, th);
387         if (rc != 0)
388                 GOTO(out, rc);
389
390         rc = dt_record_write(env, osp->opd_last_used_oid_file, lb_oid,
391                              &oid_off, th);
392         if (rc != 0) {
393                 CERROR("%s: can not write to last seq file: rc = %d\n",
394                         osp->opd_obd->obd_name, rc);
395                 GOTO(out, rc);
396         }
397         rc = dt_record_write(env, osp->opd_last_used_seq_file, lb_oseq,
398                              &oseq_off, th);
399         if (rc) {
400                 CERROR("%s: can not write to last seq file: rc = %d\n",
401                         osp->opd_obd->obd_name, rc);
402                 GOTO(out, rc);
403         }
404 out:
405         dt_trans_stop(env, osp->opd_storage, th);
406         RETURN(rc);
407 }
408
409 /**
410  * Switch to another sequence
411  *
412  * When a current sequence has no available IDs left, OSP has to switch to
413  * another new sequence. OSP requests it using the regular FLDB protocol
414  * and stores synchronously before that is used in precreated. This is needed
415  * to basically have the sequences referenced (not orphaned), otherwise it's
416  * possible that OST has some objects precreated and the clients have data
417  * written to it, but after MDT failover nobody refers those objects and OSP
418  * has no idea that the sequence need cleanup to be done.
419  * While this is very expensive operation, it's supposed to happen very very
420  * infrequently because sequence has 2^32 or 2^48 objects (depending on type)
421  *
422  * \param[in] env       LU environment provided by the caller
423  * \param[in] osp       OSP device
424  *
425  * \retval 0            on success
426  * \retval negative     negated errno on error
427  */
428 static int osp_precreate_rollover_new_seq(struct lu_env *env,
429                                           struct osp_device *osp)
430 {
431         struct lu_fid   *fid = &osp_env_info(env)->osi_fid;
432         struct lu_fid   *last_fid = &osp->opd_last_used_fid;
433         int             rc;
434         ENTRY;
435
436         rc = seq_client_get_seq(env, osp->opd_obd->u.cli.cl_seq, &fid->f_seq);
437         if (rc != 0) {
438                 CERROR("%s: alloc fid error: rc = %d\n",
439                        osp->opd_obd->obd_name, rc);
440                 RETURN(rc);
441         }
442
443         fid->f_oid = 1;
444         fid->f_ver = 0;
445         LASSERTF(fid_seq(fid) != fid_seq(last_fid),
446                  "fid "DFID", last_fid "DFID"\n", PFID(fid),
447                  PFID(last_fid));
448
449         rc = osp_write_last_oid_seq_files(env, osp, fid, 1);
450         if (rc != 0) {
451                 CERROR("%s: Can not update oid/seq file: rc = %d\n",
452                        osp->opd_obd->obd_name, rc);
453                 RETURN(rc);
454         }
455
456         LCONSOLE_INFO("%s: update sequence from "LPX64" to "LPX64"\n",
457                       osp->opd_obd->obd_name, fid_seq(last_fid),
458                       fid_seq(fid));
459         /* Update last_xxx to the new seq */
460         spin_lock(&osp->opd_pre_lock);
461         osp->opd_last_used_fid = *fid;
462         osp->opd_gap_start_fid = *fid;
463         osp->opd_pre_used_fid = *fid;
464         osp->opd_pre_last_created_fid = *fid;
465         spin_unlock(&osp->opd_pre_lock);
466
467         RETURN(rc);
468 }
469
470 /**
471  * Find IDs available in current sequence
472  *
473  * The function calculates the highest possible ID and the number of IDs
474  * available in the current sequence OSP is using. The number is limited
475  * artifically by the caller (grow param) and the number of IDs available
476  * in the sequence by nature. The function doesn't require an external
477  * locking.
478  *
479  * \param[in] env       LU environment provided by the caller
480  * \param[in] osp       OSP device
481  * \param[in] fid       FID the caller wants to start with
482  * \param[in] grow      how many the caller wants
483  * \param[out] fid      the highest calculated FID
484  * \param[out] grow     the number of available IDs calculated
485  *
486  * \retval              0 on success, 1 - the sequence is empty
487  */
488 static int osp_precreate_fids(const struct lu_env *env, struct osp_device *osp,
489                               struct lu_fid *fid, int *grow)
490 {
491         struct osp_thread_info  *osi = osp_env_info(env);
492         __u64                   end;
493         int                     i = 0;
494
495         if (fid_is_idif(fid)) {
496                 struct lu_fid   *last_fid;
497                 struct ost_id   *oi = &osi->osi_oi;
498
499                 spin_lock(&osp->opd_pre_lock);
500                 last_fid = &osp->opd_pre_last_created_fid;
501                 fid_to_ostid(last_fid, oi);
502                 end = min(ostid_id(oi) + *grow, IDIF_MAX_OID);
503                 *grow = end - ostid_id(oi);
504                 ostid_set_id(oi, ostid_id(oi) + *grow);
505                 spin_unlock(&osp->opd_pre_lock);
506
507                 if (*grow == 0)
508                         return 1;
509
510                 ostid_to_fid(fid, oi, osp->opd_index);
511                 return 0;
512         }
513
514         spin_lock(&osp->opd_pre_lock);
515         *fid = osp->opd_pre_last_created_fid;
516         end = fid->f_oid;
517         end = min((end + *grow), (__u64)LUSTRE_DATA_SEQ_MAX_WIDTH);
518         *grow = end - fid->f_oid;
519         fid->f_oid += end - fid->f_oid;
520         spin_unlock(&osp->opd_pre_lock);
521
522         CDEBUG(D_INFO, "Expect %d, actual %d ["DFID" -- "DFID"]\n",
523                *grow, i, PFID(fid), PFID(&osp->opd_pre_last_created_fid));
524
525         return *grow > 0 ? 0 : 1;
526 }
527
528 /**
529  * Prepare and send precreate RPC
530  *
531  * The function finds how many objects should be precreated.  Then allocates,
532  * prepares and schedules precreate RPC synchronously. Upon reply the function
533  * wake ups the threads waiting for the new objects on this target. If the
534  * target wasn't able to create all the objects requested, then the next
535  * precreate will be asking less objects (i.e. slow precreate down).
536  *
537  * \param[in] env       LU environment provided by the caller
538  * \param[in] d         OSP device
539  *
540  * \retval 0            on success
541  * \retval negative     negated errno on error
542  **/
543 static int osp_precreate_send(const struct lu_env *env, struct osp_device *d)
544 {
545         struct osp_thread_info  *oti = osp_env_info(env);
546         struct ptlrpc_request   *req;
547         struct obd_import       *imp;
548         struct ost_body         *body;
549         int                      rc, grow, diff;
550         struct lu_fid           *fid = &oti->osi_fid;
551         ENTRY;
552
553         /* don't precreate new objects till OST healthy and has free space */
554         if (unlikely(d->opd_pre_status)) {
555                 CDEBUG(D_INFO, "%s: don't send new precreate: rc = %d\n",
556                        d->opd_obd->obd_name, d->opd_pre_status);
557                 RETURN(0);
558         }
559
560         /*
561          * if not connection/initialization is compeleted, ignore
562          */
563         imp = d->opd_obd->u.cli.cl_import;
564         LASSERT(imp);
565
566         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
567         if (req == NULL)
568                 RETURN(-ENOMEM);
569         req->rq_request_portal = OST_CREATE_PORTAL;
570         /* we should not resend create request - anyway we will have delorphan
571          * and kill these objects */
572         req->rq_no_delay = req->rq_no_resend = 1;
573
574         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
575         if (rc) {
576                 ptlrpc_request_free(req);
577                 RETURN(rc);
578         }
579
580         spin_lock(&d->opd_pre_lock);
581         if (d->opd_pre_create_count > d->opd_pre_max_create_count / 2)
582                 d->opd_pre_create_count = d->opd_pre_max_create_count / 2;
583         grow = d->opd_pre_create_count;
584         spin_unlock(&d->opd_pre_lock);
585
586         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
587         LASSERT(body);
588
589         *fid = d->opd_pre_last_created_fid;
590         rc = osp_precreate_fids(env, d, fid, &grow);
591         if (rc == 1) {
592                 /* Current seq has been used up*/
593                 if (!osp_is_fid_client(d)) {
594                         osp_pre_update_status(d, -ENOSPC);
595                         rc = -ENOSPC;
596                 }
597                 wake_up(&d->opd_pre_waitq);
598                 GOTO(out_req, rc);
599         }
600
601         if (!osp_is_fid_client(d)) {
602                 /* Non-FID client will always send seq 0 because of
603                  * compatiblity */
604                 LASSERTF(fid_is_idif(fid), "Invalid fid "DFID"\n", PFID(fid));
605                 fid->f_seq = 0;
606         }
607
608         fid_to_ostid(fid, &body->oa.o_oi);
609         body->oa.o_valid = OBD_MD_FLGROUP;
610
611         ptlrpc_request_set_replen(req);
612
613         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_FAKE_PRECREATE))
614                 GOTO(ready, rc = 0);
615
616         rc = ptlrpc_queue_wait(req);
617         if (rc) {
618                 CERROR("%s: can't precreate: rc = %d\n", d->opd_obd->obd_name,
619                        rc);
620                 GOTO(out_req, rc);
621         }
622         LASSERT(req->rq_transno == 0);
623
624         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
625         if (body == NULL)
626                 GOTO(out_req, rc = -EPROTO);
627
628         ostid_to_fid(fid, &body->oa.o_oi, d->opd_index);
629
630 ready:
631         if (osp_fid_diff(fid, &d->opd_pre_used_fid) <= 0) {
632                 CERROR("%s: precreate fid "DFID" < local used fid "DFID
633                        ": rc = %d\n", d->opd_obd->obd_name,
634                        PFID(fid), PFID(&d->opd_pre_used_fid), -ESTALE);
635                 GOTO(out_req, rc = -ESTALE);
636         }
637
638         diff = osp_fid_diff(fid, &d->opd_pre_last_created_fid);
639
640         spin_lock(&d->opd_pre_lock);
641         if (diff < grow) {
642                 /* the OST has not managed to create all the
643                  * objects we asked for */
644                 d->opd_pre_create_count = max(diff, OST_MIN_PRECREATE);
645                 d->opd_pre_create_slow = 1;
646         } else {
647                 /* the OST is able to keep up with the work,
648                  * we could consider increasing create_count
649                  * next time if needed */
650                 d->opd_pre_create_slow = 0;
651         }
652
653         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
654         fid_to_ostid(fid, &body->oa.o_oi);
655
656         d->opd_pre_last_created_fid = *fid;
657         spin_unlock(&d->opd_pre_lock);
658
659         CDEBUG(D_HA, "%s: current precreated pool: "DFID"-"DFID"\n",
660                d->opd_obd->obd_name, PFID(&d->opd_pre_used_fid),
661                PFID(&d->opd_pre_last_created_fid));
662 out_req:
663         /* now we can wakeup all users awaiting for objects */
664         osp_pre_update_status(d, rc);
665         wake_up(&d->opd_pre_user_waitq);
666
667         ptlrpc_req_finished(req);
668         RETURN(rc);
669 }
670
671 /**
672  * Get last precreated object from target (OST)
673  *
674  * Sends synchronous RPC to the target (OST) to learn the last precreated
675  * object. This later is used to remove all unused objects (cleanup orphan
676  * procedure). Also, the next object after one we got will be used as a
677  * starting point for the new precreates.
678  *
679  * \param[in] env       LU environment provided by the caller
680  * \param[in] d         OSP device
681  *
682  * \retval 0            on success
683  * \retval negative     negated errno on error
684  **/
685 static int osp_get_lastfid_from_ost(const struct lu_env *env,
686                                     struct osp_device *d)
687 {
688         struct ptlrpc_request   *req = NULL;
689         struct obd_import       *imp;
690         struct lu_fid           *last_fid;
691         char                    *tmp;
692         int                     rc;
693         ENTRY;
694
695         imp = d->opd_obd->u.cli.cl_import;
696         LASSERT(imp);
697
698         req = ptlrpc_request_alloc(imp, &RQF_OST_GET_INFO_LAST_FID);
699         if (req == NULL)
700                 RETURN(-ENOMEM);
701
702         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_KEY, RCL_CLIENT,
703                              sizeof(KEY_LAST_FID));
704
705         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GET_INFO);
706         if (rc) {
707                 ptlrpc_request_free(req);
708                 RETURN(rc);
709         }
710
711         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_KEY);
712         memcpy(tmp, KEY_LAST_FID, sizeof(KEY_LAST_FID));
713
714         req->rq_no_delay = req->rq_no_resend = 1;
715         last_fid = req_capsule_client_get(&req->rq_pill, &RMF_FID);
716         fid_cpu_to_le(last_fid, &d->opd_last_used_fid);
717
718         ptlrpc_request_set_replen(req);
719
720         rc = ptlrpc_queue_wait(req);
721         if (rc) {
722                 /* bad-bad OST.. let sysadm sort this out */
723                 if (rc == -ENOTSUPP) {
724                         CERROR("%s: server does not support FID: rc = %d\n",
725                                d->opd_obd->obd_name, -ENOTSUPP);
726                 }
727                 ptlrpc_set_import_active(imp, 0);
728                 GOTO(out, rc);
729         }
730
731         last_fid = req_capsule_server_get(&req->rq_pill, &RMF_FID);
732         if (last_fid == NULL) {
733                 CERROR("%s: Got last_fid failed.\n", d->opd_obd->obd_name);
734                 GOTO(out, rc = -EPROTO);
735         }
736
737         if (!fid_is_sane(last_fid)) {
738                 CERROR("%s: Got insane last_fid "DFID"\n",
739                        d->opd_obd->obd_name, PFID(last_fid));
740                 GOTO(out, rc = -EPROTO);
741         }
742
743         /* Only update the last used fid, if the OST has objects for
744          * this sequence, i.e. fid_oid > 0 */
745         if (fid_oid(last_fid) > 0)
746                 d->opd_last_used_fid = *last_fid;
747
748         CDEBUG(D_HA, "%s: Got last_fid "DFID"\n", d->opd_obd->obd_name,
749                PFID(last_fid));
750
751 out:
752         ptlrpc_req_finished(req);
753         RETURN(rc);
754 }
755
756 /**
757  * Cleanup orphans on OST
758  *
759  * This function is called in a contex of a dedicated thread handling
760  * all the precreation suff. The function waits till local recovery
761  * is complete, then identify all the unreferenced objects (orphans)
762  * using the highest ID referenced by a local and the highest object
763  * precreated by the target. The found range is a subject to removal
764  * using specially flagged RPC. During this process OSP is marked
765  * unavailable for new objects.
766  *
767  * \param[in] env       LU environment provided by the caller
768  * \param[in] d         OSP device
769  *
770  * \retval 0            on success
771  * \retval negative     negated errno on error
772  */
773 static int osp_precreate_cleanup_orphans(struct lu_env *env,
774                                          struct osp_device *d)
775 {
776         struct osp_thread_info  *osi = osp_env_info(env);
777         struct lu_fid           *last_fid = &osi->osi_fid;
778         struct ptlrpc_request   *req = NULL;
779         struct obd_import       *imp;
780         struct ost_body         *body;
781         struct l_wait_info       lwi = { 0 };
782         int                      update_status = 0;
783         int                      rc;
784         int                      diff;
785
786         ENTRY;
787
788         /*
789          * wait for local recovery to finish, so we can cleanup orphans
790          * orphans are all objects since "last used" (assigned), but
791          * there might be objects reserved and in some cases they won't
792          * be used. we can't cleanup them till we're sure they won't be
793          * used. also can't we allow new reservations because they may
794          * end up getting orphans being cleaned up below. so we block
795          * new reservations and wait till all reserved objects either
796          * user or released.
797          */
798         spin_lock(&d->opd_pre_lock);
799         d->opd_pre_recovering = 1;
800         spin_unlock(&d->opd_pre_lock);
801         /*
802          * The locking above makes sure the opd_pre_reserved check below will
803          * catch all osp_precreate_reserve() calls who find
804          * "!opd_pre_recovering".
805          */
806         l_wait_event(d->opd_pre_waitq,
807                      (!d->opd_pre_reserved && d->opd_recovery_completed) ||
808                      !osp_precreate_running(d) || d->opd_got_disconnected,
809                      &lwi);
810         if (!osp_precreate_running(d) || d->opd_got_disconnected)
811                 GOTO(out, rc = -EAGAIN);
812
813         CDEBUG(D_HA, "%s: going to cleanup orphans since "DFID"\n",
814                d->opd_obd->obd_name, PFID(&d->opd_last_used_fid));
815
816         *last_fid = d->opd_last_used_fid;
817         /* The OSP should already get the valid seq now */
818         LASSERT(!fid_is_zero(last_fid));
819         if (fid_oid(&d->opd_last_used_fid) < 2) {
820                 /* lastfid looks strange... ask OST */
821                 rc = osp_get_lastfid_from_ost(env, d);
822                 if (rc)
823                         GOTO(out, rc);
824         }
825
826         imp = d->opd_obd->u.cli.cl_import;
827         LASSERT(imp);
828
829         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
830         if (req == NULL)
831                 GOTO(out, rc = -ENOMEM);
832
833         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
834         if (rc) {
835                 ptlrpc_request_free(req);
836                 req = NULL;
837                 GOTO(out, rc);
838         }
839
840         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
841         if (body == NULL)
842                 GOTO(out, rc = -EPROTO);
843
844         body->oa.o_flags = OBD_FL_DELORPHAN;
845         body->oa.o_valid = OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
846
847         fid_to_ostid(&d->opd_last_used_fid, &body->oa.o_oi);
848
849         ptlrpc_request_set_replen(req);
850
851         /* Don't resend the delorphan req */
852         req->rq_no_resend = req->rq_no_delay = 1;
853
854         rc = ptlrpc_queue_wait(req);
855         if (rc) {
856                 update_status = 1;
857                 GOTO(out, rc);
858         }
859
860         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
861         if (body == NULL)
862                 GOTO(out, rc = -EPROTO);
863
864         /*
865          * OST provides us with id new pool starts from in body->oa.o_id
866          */
867         ostid_to_fid(last_fid, &body->oa.o_oi, d->opd_index);
868
869         spin_lock(&d->opd_pre_lock);
870         diff = osp_fid_diff(&d->opd_last_used_fid, last_fid);
871         if (diff > 0) {
872                 d->opd_pre_create_count = OST_MIN_PRECREATE + diff;
873                 d->opd_pre_last_created_fid = d->opd_last_used_fid;
874         } else {
875                 d->opd_pre_create_count = OST_MIN_PRECREATE;
876                 d->opd_pre_last_created_fid = *last_fid;
877         }
878         /*
879          * This empties the pre-creation pool and effectively blocks any new
880          * reservations.
881          */
882         LASSERT(fid_oid(&d->opd_pre_last_created_fid) <=
883                 LUSTRE_DATA_SEQ_MAX_WIDTH);
884         d->opd_pre_used_fid = d->opd_pre_last_created_fid;
885         d->opd_pre_create_slow = 0;
886         spin_unlock(&d->opd_pre_lock);
887
888         CDEBUG(D_HA, "%s: Got last_id "DFID" from OST, last_created "DFID
889                "last_used is "DFID"\n", d->opd_obd->obd_name, PFID(last_fid),
890                PFID(&d->opd_pre_last_created_fid), PFID(&d->opd_last_used_fid));
891 out:
892         if (req)
893                 ptlrpc_req_finished(req);
894
895         spin_lock(&d->opd_pre_lock);
896         d->opd_pre_recovering = 0;
897         spin_unlock(&d->opd_pre_lock);
898
899         /*
900          * If rc is zero, the pre-creation window should have been emptied.
901          * Since waking up the herd would be useless without pre-created
902          * objects, we defer the signal to osp_precreate_send() in that case.
903          */
904         if (rc != 0) {
905                 if (update_status) {
906                         CERROR("%s: cannot cleanup orphans: rc = %d\n",
907                                d->opd_obd->obd_name, rc);
908                         /* we can't proceed from here, OST seem to
909                          * be in a bad shape, better to wait for
910                          * a new instance of the server and repeat
911                          * from the beginning. notify possible waiters
912                          * this OSP isn't quite functional yet */
913                         osp_pre_update_status(d, rc);
914                 } else {
915                         wake_up(&d->opd_pre_user_waitq);
916                 }
917         }
918
919         RETURN(rc);
920 }
921
922 /**
923  * Update precreate status using statfs data
924  *
925  * The function decides whether this OSP should be used for new objects.
926  * IOW, whether this OST is used up or has some free space. Cached statfs
927  * data is used to make this decision. If the latest result of statfs
928  * request (rc argument) is not success, then just mark OSP unavailable
929  * right away.
930
931  * Add a bit of hysteresis so this flag isn't continually flapping,
932  * and ensure that new files don't get extremely fragmented due to
933  * only a small amount of available space in the filesystem.
934  * We want to set the NOSPC flag when there is less than ~0.1% free
935  * and clear it when there is at least ~0.2% free space, so:
936  *                   avail < ~0.1% max          max = avail + used
937  *            1025 * avail < avail + used       used = blocks - free
938  *            1024 * avail < used
939  *            1024 * avail < blocks - free
940  *                   avail < ((blocks - free) >> 10)
941  *
942  * On very large disk, say 16TB 0.1% will be 16 GB. We don't want to
943  * lose that amount of space so in those cases we report no space left
944  * if their is less than 1 GB left.
945  * the function updates current precreation status used: functional or not
946  *
947  * \param[in] d         OSP device
948  * \param[in] rc        new precreate status for device \a d
949  *
950  * \retval 0            on success
951  * \retval negative     negated errno on error
952  */
953 void osp_pre_update_status(struct osp_device *d, int rc)
954 {
955         struct obd_statfs       *msfs = &d->opd_statfs;
956         int                      old = d->opd_pre_status;
957         __u64                    used;
958
959         d->opd_pre_status = rc;
960         if (rc)
961                 goto out;
962
963         if (likely(msfs->os_type)) {
964                 used = min_t(__u64, (msfs->os_blocks - msfs->os_bfree) >> 10,
965                                     1 << 30);
966                 if ((msfs->os_ffree < 32) || (msfs->os_bavail < used)) {
967                         d->opd_pre_status = -ENOSPC;
968                         if (old != -ENOSPC)
969                                 CDEBUG(D_INFO, "%s: status: "LPU64" blocks, "
970                                        LPU64" free, "LPU64" used, "LPU64" "
971                                        "avail -> %d: rc = %d\n",
972                                        d->opd_obd->obd_name, msfs->os_blocks,
973                                        msfs->os_bfree, used, msfs->os_bavail,
974                                        d->opd_pre_status, rc);
975                         CDEBUG(D_INFO,
976                                "non-committed changes: %u, in progress: %u\n",
977                                atomic_read(&d->opd_syn_changes),
978                                atomic_read(&d->opd_syn_rpc_in_progress));
979                 } else if (old == -ENOSPC) {
980                         d->opd_pre_status = 0;
981                         spin_lock(&d->opd_pre_lock);
982                         d->opd_pre_create_slow = 0;
983                         d->opd_pre_create_count = OST_MIN_PRECREATE;
984                         spin_unlock(&d->opd_pre_lock);
985                         wake_up(&d->opd_pre_waitq);
986                         CDEBUG(D_INFO, "%s: no space: "LPU64" blocks, "LPU64
987                                " free, "LPU64" used, "LPU64" avail -> %d: "
988                                "rc = %d\n", d->opd_obd->obd_name,
989                                msfs->os_blocks, msfs->os_bfree, used,
990                                msfs->os_bavail, d->opd_pre_status, rc);
991                 }
992         }
993
994 out:
995         wake_up(&d->opd_pre_user_waitq);
996 }
997
998 /**
999  * Initialize FID for precreation
1000  *
1001  * For a just created new target, a new sequence should be taken.
1002  * The function checks there is no IDIF in use (if the target was
1003  * added with the older version of Lustre), then requests a new
1004  * sequence from FLDB using the regular protocol. Then this new
1005  * sequence is stored on a persisten storage synchronously to prevent
1006  * possible object leakage (for the detail see the description for
1007  * osp_precreate_rollover_new_seq()).
1008  *
1009  * \param[in] osp       OSP device
1010  *
1011  * \retval 0            on success
1012  * \retval negative     negated errno on error
1013  */
1014 int osp_init_pre_fid(struct osp_device *osp)
1015 {
1016         struct lu_env           env;
1017         struct osp_thread_info  *osi;
1018         struct lu_client_seq    *cli_seq;
1019         struct lu_fid           *last_fid;
1020         int                     rc;
1021         ENTRY;
1022
1023         LASSERT(osp->opd_pre != NULL);
1024
1025         /* Return if last_used fid has been initialized */
1026         if (!fid_is_zero(&osp->opd_last_used_fid))
1027                 RETURN(0);
1028
1029         rc = lu_env_init(&env, osp->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1030         if (rc) {
1031                 CERROR("%s: init env error: rc = %d\n",
1032                        osp->opd_obd->obd_name, rc);
1033                 RETURN(rc);
1034         }
1035
1036         osi = osp_env_info(&env);
1037         last_fid = &osi->osi_fid;
1038         fid_zero(last_fid);
1039         /* For a freshed fs, it will allocate a new sequence first */
1040         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1041                 cli_seq = osp->opd_obd->u.cli.cl_seq;
1042                 rc = seq_client_get_seq(&env, cli_seq, &last_fid->f_seq);
1043                 if (rc != 0) {
1044                         CERROR("%s: alloc fid error: rc = %d\n",
1045                                osp->opd_obd->obd_name, rc);
1046                         GOTO(out, rc);
1047                 }
1048         } else {
1049                 last_fid->f_seq = fid_idif_seq(0, osp->opd_index);
1050         }
1051         last_fid->f_oid = 1;
1052         last_fid->f_ver = 0;
1053
1054         spin_lock(&osp->opd_pre_lock);
1055         osp->opd_last_used_fid = *last_fid;
1056         osp->opd_pre_used_fid = *last_fid;
1057         osp->opd_pre_last_created_fid = *last_fid;
1058         spin_unlock(&osp->opd_pre_lock);
1059         rc = osp_write_last_oid_seq_files(&env, osp, last_fid, 1);
1060         if (rc != 0) {
1061                 CERROR("%s: write fid error: rc = %d\n",
1062                        osp->opd_obd->obd_name, rc);
1063                 GOTO(out, rc);
1064         }
1065 out:
1066         lu_env_fini(&env);
1067         RETURN(rc);
1068 }
1069
1070 /**
1071  * The core of precreate functionality
1072  *
1073  * The function implements the main precreation loop. Basically it
1074  * involves connecting to the target, precerate FID initialization,
1075  * identifying and removing orphans, then serving precreation. As
1076  * part of the latter, the thread is responsible for statfs data
1077  * updates. The precreation is mostly driven by another threads
1078  * asking for new OST objects - those askers wake the thread when
1079  * the number of precreated objects reach low watermark.
1080  * After a disconnect, the sequence above repeats. This is keep going
1081  * until the thread is requested to stop.
1082  *
1083  * \param[in] _arg      private data the thread (OSP device to handle)
1084  *
1085  * \retval 0            on success
1086  * \retval negative     negated errno on error
1087  */
1088 static int osp_precreate_thread(void *_arg)
1089 {
1090         struct osp_device       *d = _arg;
1091         struct ptlrpc_thread    *thread = &d->opd_pre_thread;
1092         struct l_wait_info       lwi = { 0 };
1093         struct l_wait_info       lwi2 = LWI_TIMEOUT(cfs_time_seconds(5),
1094                                                     back_to_sleep, NULL);
1095         struct lu_env            env;
1096         int                      rc;
1097
1098         ENTRY;
1099
1100         rc = lu_env_init(&env, d->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1101         if (rc) {
1102                 CERROR("%s: init env error: rc = %d\n", d->opd_obd->obd_name,
1103                        rc);
1104                 RETURN(rc);
1105         }
1106
1107         spin_lock(&d->opd_pre_lock);
1108         thread->t_flags = SVC_RUNNING;
1109         spin_unlock(&d->opd_pre_lock);
1110         wake_up(&thread->t_ctl_waitq);
1111
1112         while (osp_precreate_running(d)) {
1113                 /*
1114                  * need to be connected to OST
1115                  */
1116                 while (osp_precreate_running(d)) {
1117                         l_wait_event(d->opd_pre_waitq,
1118                                      !osp_precreate_running(d) ||
1119                                      d->opd_new_connection,
1120                                      &lwi);
1121
1122                         if (!d->opd_new_connection)
1123                                 continue;
1124
1125                         d->opd_new_connection = 0;
1126                         d->opd_got_disconnected = 0;
1127                         break;
1128                 }
1129
1130                 if (!osp_precreate_running(d))
1131                         break;
1132
1133                 LASSERT(d->opd_obd->u.cli.cl_seq != NULL);
1134                 /* Sigh, fid client is not ready yet */
1135                 if (d->opd_obd->u.cli.cl_seq->lcs_exp == NULL)
1136                         continue;
1137
1138                 /* Init fid for osp_precreate if necessary */
1139                 rc = osp_init_pre_fid(d);
1140                 if (rc != 0) {
1141                         class_export_put(d->opd_exp);
1142                         d->opd_obd->u.cli.cl_seq->lcs_exp = NULL;
1143                         CERROR("%s: init pre fid error: rc = %d\n",
1144                                d->opd_obd->obd_name, rc);
1145                         continue;
1146                 }
1147
1148                 if (osp_statfs_update(d)) {
1149                         l_wait_event(d->opd_pre_waitq,
1150                                      !osp_precreate_running(d), &lwi2);
1151                         continue;
1152                 }
1153
1154                 /*
1155                  * Clean up orphans or recreate missing objects.
1156                  */
1157                 rc = osp_precreate_cleanup_orphans(&env, d);
1158                 if (rc != 0)
1159                         continue;
1160                 /*
1161                  * connected, can handle precreates now
1162                  */
1163                 while (osp_precreate_running(d)) {
1164                         l_wait_event(d->opd_pre_waitq,
1165                                      !osp_precreate_running(d) ||
1166                                      osp_precreate_near_empty(&env, d) ||
1167                                      osp_statfs_need_update(d) ||
1168                                      d->opd_got_disconnected, &lwi);
1169
1170                         if (!osp_precreate_running(d))
1171                                 break;
1172
1173                         /* something happened to the connection
1174                          * have to start from the beginning */
1175                         if (d->opd_got_disconnected)
1176                                 break;
1177
1178                         if (osp_statfs_need_update(d))
1179                                 if (osp_statfs_update(d))
1180                                         break;
1181
1182                         /* To avoid handling different seq in precreate/orphan
1183                          * cleanup, it will hold precreate until current seq is
1184                          * used up. */
1185                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1186                             !osp_create_end_seq(&env, d)))
1187                                 continue;
1188
1189                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1190                                      osp_create_end_seq(&env, d))) {
1191                                 LCONSOLE_INFO("%s:"LPX64" is used up."
1192                                               " Update to new seq\n",
1193                                               d->opd_obd->obd_name,
1194                                          fid_seq(&d->opd_pre_last_created_fid));
1195                                 rc = osp_precreate_rollover_new_seq(&env, d);
1196                                 if (rc)
1197                                         continue;
1198                         }
1199
1200                         if (osp_precreate_near_empty(&env, d)) {
1201                                 rc = osp_precreate_send(&env, d);
1202                                 /* osp_precreate_send() sets opd_pre_status
1203                                  * in case of error, that prevent the using of
1204                                  * failed device. */
1205                                 if (rc < 0 && rc != -ENOSPC &&
1206                                     rc != -ETIMEDOUT && rc != -ENOTCONN)
1207                                         CERROR("%s: cannot precreate objects:"
1208                                                " rc = %d\n",
1209                                                d->opd_obd->obd_name, rc);
1210                         }
1211                 }
1212         }
1213
1214         thread->t_flags = SVC_STOPPED;
1215         lu_env_fini(&env);
1216         wake_up(&thread->t_ctl_waitq);
1217
1218         RETURN(0);
1219 }
1220
1221 /**
1222  * Check when to stop to wait for precreate objects.
1223  *
1224  * The caller wanting a new OST object can't wait undefinitely. The
1225  * function checks for few conditions including available new OST
1226  * objects, disconnected OST, lack of space with no pending destroys,
1227  * etc. IOW, it checks whether the current OSP state is good to keep
1228  * waiting or it's better to give up.
1229  *
1230  * \param[in] env       LU environment provided by the caller
1231  * \param[in] d         OSP device
1232  *
1233  * \retval              0 - keep waiting, 1 - no luck
1234  */
1235 static int osp_precreate_ready_condition(const struct lu_env *env,
1236                                          struct osp_device *d)
1237 {
1238         if (d->opd_pre_recovering)
1239                 return 0;
1240
1241         /* ready if got enough precreated objects */
1242         /* we need to wait for others (opd_pre_reserved) and our object (+1) */
1243         if (d->opd_pre_reserved + 1 < osp_objs_precreated(env, d))
1244                 return 1;
1245
1246         /* ready if OST reported no space and no destroys in progress */
1247         if (atomic_read(&d->opd_syn_changes) +
1248             atomic_read(&d->opd_syn_rpc_in_progress) == 0 &&
1249             d->opd_pre_status == -ENOSPC)
1250                 return 1;
1251
1252         /* Bail out I/O fails to OST */
1253         if (d->opd_pre_status != 0 &&
1254             d->opd_pre_status != -EAGAIN &&
1255             d->opd_pre_status != -ENODEV &&
1256             d->opd_pre_status != -ENOTCONN &&
1257             d->opd_pre_status != -ENOSPC) {
1258                 /* DEBUG LU-3230 */
1259                 if (d->opd_pre_status != -EIO)
1260                         CERROR("%s: precreate failed opd_pre_status %d\n",
1261                                d->opd_obd->obd_name, d->opd_pre_status);
1262                 return 1;
1263         }
1264
1265         return 0;
1266 }
1267
1268 static int osp_precreate_timeout_condition(void *data)
1269 {
1270         struct osp_device *d = data;
1271
1272         CDEBUG(D_HA, "%s: slow creates, last="DFID", next="DFID", "
1273               "reserved="LPU64", syn_changes=%u, "
1274               "syn_rpc_in_progress=%d, status=%d\n",
1275               d->opd_obd->obd_name, PFID(&d->opd_pre_last_created_fid),
1276               PFID(&d->opd_pre_used_fid), d->opd_pre_reserved,
1277               atomic_read(&d->opd_syn_changes),
1278               atomic_read(&d->opd_syn_rpc_in_progress),
1279               d->opd_pre_status);
1280
1281         return 1;
1282 }
1283
1284 /**
1285  * Reserve object in precreate pool
1286  *
1287  * When the caller wants to create a new object on this target (target
1288  * represented by the given OSP), it should declare this intention using
1289  * a regular ->dt_declare_create() OSD API method. Then OSP will be trying
1290  * to reserve an object in the existing precreated pool or wait up to
1291  * obd_timeout for the available object to appear in the pool (a dedicated
1292  * thread will be doing real precreation in background). The object can be
1293  * consumed later with osp_precreate_get_fid() or be released with call to
1294  * lu_object_put(). Notice the function doesn't reserve a specific ID, just
1295  * some ID. The actual ID assignment happen in osp_precreate_get_fid().
1296  * If the space on the target is short and there is a pending object destroy,
1297  * then the function forces local commit to speedup space release (see
1298  * osp_sync.c for the details).
1299  *
1300  * \param[in] env       LU environment provided by the caller
1301  * \param[in] d         OSP device
1302  *
1303  * \retval              0 on success
1304  * \retval              -ENOSPC when no space on OST
1305  * \retval              -EAGAIN try later, slow precreation in progress
1306  * \retval              -EIO when no access to OST
1307  */
1308 int osp_precreate_reserve(const struct lu_env *env, struct osp_device *d)
1309 {
1310         struct l_wait_info       lwi;
1311         cfs_time_t               expire = cfs_time_shift(obd_timeout);
1312         int                      precreated, rc;
1313
1314         ENTRY;
1315
1316         LASSERTF(osp_objs_precreated(env, d) >= 0, "Last created FID "DFID
1317                  "Next FID "DFID"\n", PFID(&d->opd_pre_last_created_fid),
1318                  PFID(&d->opd_pre_used_fid));
1319
1320         /* opd_pre_max_create_count 0 to not use specified OST. */
1321         if (d->opd_pre_max_create_count == 0)
1322                 RETURN(-ENOBUFS);
1323
1324         /*
1325          * wait till:
1326          *  - preallocation is done
1327          *  - no free space expected soon
1328          *  - can't connect to OST for too long (obd_timeout)
1329          *  - OST can allocate fid sequence.
1330          */
1331         while ((rc = d->opd_pre_status) == 0 || rc == -ENOSPC ||
1332                 rc == -ENODEV || rc == -EAGAIN || rc == -ENOTCONN) {
1333
1334                 /*
1335                  * increase number of precreations
1336                  */
1337                 precreated = osp_objs_precreated(env, d);
1338                 if (d->opd_pre_create_count < d->opd_pre_max_create_count &&
1339                     d->opd_pre_create_slow == 0 &&
1340                     precreated <= (d->opd_pre_create_count / 4 + 1)) {
1341                         spin_lock(&d->opd_pre_lock);
1342                         d->opd_pre_create_slow = 1;
1343                         d->opd_pre_create_count *= 2;
1344                         spin_unlock(&d->opd_pre_lock);
1345                 }
1346
1347                 spin_lock(&d->opd_pre_lock);
1348                 precreated = osp_objs_precreated(env, d);
1349                 if (precreated > d->opd_pre_reserved &&
1350                     !d->opd_pre_recovering) {
1351                         d->opd_pre_reserved++;
1352                         spin_unlock(&d->opd_pre_lock);
1353                         rc = 0;
1354
1355                         /* XXX: don't wake up if precreation is in progress */
1356                         if (osp_precreate_near_empty_nolock(env, d) &&
1357                            !osp_precreate_end_seq_nolock(env, d))
1358                                 wake_up(&d->opd_pre_waitq);
1359
1360                         break;
1361                 }
1362                 spin_unlock(&d->opd_pre_lock);
1363
1364                 /*
1365                  * all precreated objects have been used and no-space
1366                  * status leave us no chance to succeed very soon
1367                  * but if there is destroy in progress, then we should
1368                  * wait till that is done - some space might be released
1369                  */
1370                 if (unlikely(rc == -ENOSPC)) {
1371                         if (atomic_read(&d->opd_syn_changes)) {
1372                                 /* force local commit to release space */
1373                                 dt_commit_async(env, d->opd_storage);
1374                         }
1375                         if (atomic_read(&d->opd_syn_rpc_in_progress)) {
1376                                 /* just wait till destroys are done */
1377                                 /* see l_wait_even() few lines below */
1378                         }
1379                         if (atomic_read(&d->opd_syn_changes) +
1380                             atomic_read(&d->opd_syn_rpc_in_progress) == 0) {
1381                                 /* no hope for free space */
1382                                 break;
1383                         }
1384                 }
1385
1386                 /* XXX: don't wake up if precreation is in progress */
1387                 wake_up(&d->opd_pre_waitq);
1388
1389                 lwi = LWI_TIMEOUT(expire - cfs_time_current(),
1390                                 osp_precreate_timeout_condition, d);
1391                 if (cfs_time_aftereq(cfs_time_current(), expire)) {
1392                         rc = -ETIMEDOUT;
1393                         break;
1394                 }
1395
1396                 l_wait_event(d->opd_pre_user_waitq,
1397                              osp_precreate_ready_condition(env, d), &lwi);
1398         }
1399
1400         RETURN(rc);
1401 }
1402
1403 /**
1404  * Get a FID from precreation pool
1405  *
1406  * The function is a companion for osp_precreate_reserve() - it assigns
1407  * a specific FID from the precreate. The function should be called only
1408  * if the call to osp_precreate_reserve() was successful. The function
1409  * updates a local storage to remember the highest object ID referenced
1410  * by the node in the given sequence.
1411  *
1412  * A very importan details: this is supposed to be called once the
1413  * transaction is started, so on-disk update will be atomic with the
1414  * data (like LOVEA) refering this object. Then the object won't be leaked:
1415  * either it's referenced by the committed transaction or it's a subject
1416  * to the orphan cleanup procedure.
1417  *
1418  * \param[in] env       LU environment provided by the caller
1419  * \param[in] d         OSP device
1420  * \param[out] fid      generated FID
1421  *
1422  * \retval 0            on success
1423  * \retval negative     negated errno on error
1424  */
1425 int osp_precreate_get_fid(const struct lu_env *env, struct osp_device *d,
1426                           struct lu_fid *fid)
1427 {
1428         /* grab next id from the pool */
1429         spin_lock(&d->opd_pre_lock);
1430
1431         LASSERTF(osp_fid_diff(&d->opd_pre_used_fid,
1432                              &d->opd_pre_last_created_fid) < 0,
1433                  "next fid "DFID" last created fid "DFID"\n",
1434                  PFID(&d->opd_pre_used_fid),
1435                  PFID(&d->opd_pre_last_created_fid));
1436
1437         d->opd_pre_used_fid.f_oid++;
1438         memcpy(fid, &d->opd_pre_used_fid, sizeof(*fid));
1439         d->opd_pre_reserved--;
1440         /*
1441          * last_used_id must be changed along with getting new id otherwise
1442          * we might miscalculate gap causing object loss or leak
1443          */
1444         osp_update_last_fid(d, fid);
1445         spin_unlock(&d->opd_pre_lock);
1446
1447         /*
1448          * probably main thread suspended orphan cleanup till
1449          * all reservations are released, see comment in
1450          * osp_precreate_thread() just before orphan cleanup
1451          */
1452         if (unlikely(d->opd_pre_reserved == 0 && d->opd_pre_status))
1453                 wake_up(&d->opd_pre_waitq);
1454
1455         return 0;
1456 }
1457
1458 /*
1459  * Set size regular attribute on an object
1460  *
1461  * When a striping is created late, it's possible that size is already
1462  * initialized on the file. Then the new striping should inherit size
1463  * from the file. The function sets size on the object using the regular
1464  * protocol (OST_PUNCH).
1465  * XXX: should be re-implemented using OUT ?
1466  *
1467  * \param[in] env       LU environment provided by the caller
1468  * \param[in] dt        object
1469  * \param[in] size      size to set.
1470  *
1471  * \retval 0            on success
1472  * \retval negative     negated errno on error
1473  */
1474 int osp_object_truncate(const struct lu_env *env, struct dt_object *dt,
1475                         __u64 size)
1476 {
1477         struct osp_device       *d = lu2osp_dev(dt->do_lu.lo_dev);
1478         struct ptlrpc_request   *req = NULL;
1479         struct obd_import       *imp;
1480         struct ost_body         *body;
1481         struct obdo             *oa = NULL;
1482         int                      rc;
1483
1484         ENTRY;
1485
1486         imp = d->opd_obd->u.cli.cl_import;
1487         LASSERT(imp);
1488
1489         req = ptlrpc_request_alloc(imp, &RQF_OST_PUNCH);
1490         if (req == NULL)
1491                 RETURN(-ENOMEM);
1492
1493         /* XXX: capa support? */
1494         /* osc_set_capa_size(req, &RMF_CAPA1, capa); */
1495         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_PUNCH);
1496         if (rc) {
1497                 ptlrpc_request_free(req);
1498                 RETURN(rc);
1499         }
1500
1501         /*
1502          * XXX: decide how do we do here with resend
1503          * if we don't resend, then client may see wrong file size
1504          * if we do resend, then MDS thread can get stuck for quite long
1505          * and if we don't resend, then client will also get -EWOULDBLOCK !!
1506          * (see LU-7975 and sanity/test_27F use cases)
1507          * but let's decide not to resend/delay this truncate request to OST
1508          * and allow Client to decide to resend, in a less agressive way from
1509          * after_reply(), by returning -EINPROGRESS instead of
1510          * -EAGAIN/-EWOULDBLOCK upon return from ptlrpc_queue_wait() at the
1511          * end of this routine
1512          */
1513         req->rq_no_resend = req->rq_no_delay = 1;
1514
1515         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
1516         ptlrpc_at_set_req_timeout(req);
1517
1518         OBD_ALLOC_PTR(oa);
1519         if (oa == NULL)
1520                 GOTO(out, rc = -ENOMEM);
1521
1522         rc = fid_to_ostid(lu_object_fid(&dt->do_lu), &oa->o_oi);
1523         LASSERT(rc == 0);
1524         oa->o_size = size;
1525         oa->o_blocks = OBD_OBJECT_EOF;
1526         oa->o_valid = OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
1527                       OBD_MD_FLID | OBD_MD_FLGROUP;
1528
1529         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
1530         LASSERT(body);
1531         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
1532
1533         /* XXX: capa support? */
1534         /* osc_pack_capa(req, body, capa); */
1535
1536         ptlrpc_request_set_replen(req);
1537
1538         rc = ptlrpc_queue_wait(req);
1539         if (rc) {
1540                 /* -EWOULDBLOCK/-EAGAIN means OST is unreachable at the moment
1541                  * since we have decided not to resend/delay, but this could
1542                  * lead to wrong size to be seen at Client side and even process
1543                  * trying to open to exit/fail if not itself handling -EAGAIN.
1544                  * So it should be better to return -EINPROGRESS instead and
1545                  * leave the decision to resend at Client side in after_reply()
1546                  */
1547                 if (rc == -EWOULDBLOCK) {
1548                         rc = -EINPROGRESS;
1549                         CDEBUG(D_HA, "returning -EINPROGRESS instead of "
1550                                "-EWOULDBLOCK/-EAGAIN to allow Client to "
1551                                "resend\n");
1552                 } else {
1553                         CERROR("can't punch object: %d\n", rc);
1554                 }
1555         }
1556 out:
1557         ptlrpc_req_finished(req);
1558         if (oa)
1559                 OBD_FREE_PTR(oa);
1560         RETURN(rc);
1561 }
1562
1563 /**
1564  * Initialize precreation functionality of OSP
1565  *
1566  * Prepares all the internal structures and starts the precreate thread
1567  *
1568  * \param[in] d         OSP device
1569  *
1570  * \retval 0            on success
1571  * \retval negative     negated errno on error
1572  */
1573 int osp_init_precreate(struct osp_device *d)
1574 {
1575         struct l_wait_info       lwi = { 0 };
1576         struct task_struct              *task;
1577
1578         ENTRY;
1579
1580         OBD_ALLOC_PTR(d->opd_pre);
1581         if (d->opd_pre == NULL)
1582                 RETURN(-ENOMEM);
1583
1584         /* initially precreation isn't ready */
1585         d->opd_pre_status = -EAGAIN;
1586         fid_zero(&d->opd_pre_used_fid);
1587         d->opd_pre_used_fid.f_oid = 1;
1588         fid_zero(&d->opd_pre_last_created_fid);
1589         d->opd_pre_last_created_fid.f_oid = 1;
1590         d->opd_pre_reserved = 0;
1591         d->opd_got_disconnected = 1;
1592         d->opd_pre_create_slow = 0;
1593         d->opd_pre_create_count = OST_MIN_PRECREATE;
1594         d->opd_pre_min_create_count = OST_MIN_PRECREATE;
1595         d->opd_pre_max_create_count = OST_MAX_PRECREATE;
1596
1597         spin_lock_init(&d->opd_pre_lock);
1598         init_waitqueue_head(&d->opd_pre_waitq);
1599         init_waitqueue_head(&d->opd_pre_user_waitq);
1600         init_waitqueue_head(&d->opd_pre_thread.t_ctl_waitq);
1601
1602         /*
1603          * Initialize statfs-related things
1604          */
1605         d->opd_statfs_maxage = 5; /* default update interval */
1606         d->opd_statfs_fresh_till = cfs_time_shift(-1000);
1607         CDEBUG(D_OTHER, "current %llu, fresh till %llu\n",
1608                (unsigned long long)cfs_time_current(),
1609                (unsigned long long)d->opd_statfs_fresh_till);
1610         cfs_timer_init(&d->opd_statfs_timer, osp_statfs_timer_cb, d);
1611
1612         /*
1613          * start thread handling precreation and statfs updates
1614          */
1615         task = kthread_run(osp_precreate_thread, d,
1616                            "osp-pre-%u-%u", d->opd_index, d->opd_group);
1617         if (IS_ERR(task)) {
1618                 CERROR("can't start precreate thread %ld\n", PTR_ERR(task));
1619                 RETURN(PTR_ERR(task));
1620         }
1621
1622         l_wait_event(d->opd_pre_thread.t_ctl_waitq,
1623                      osp_precreate_running(d) || osp_precreate_stopped(d),
1624                      &lwi);
1625
1626         RETURN(0);
1627 }
1628
1629 /**
1630  * Finish precreate functionality of OSP
1631  *
1632  *
1633  * Asks all the activity (the thread, update timer) to stop, then
1634  * wait till that is done.
1635  *
1636  * \param[in] d         OSP device
1637  */
1638 void osp_precreate_fini(struct osp_device *d)
1639 {
1640         struct ptlrpc_thread *thread;
1641
1642         ENTRY;
1643
1644         cfs_timer_disarm(&d->opd_statfs_timer);
1645
1646         if (d->opd_pre == NULL)
1647                 RETURN_EXIT;
1648
1649         thread = &d->opd_pre_thread;
1650
1651         thread->t_flags = SVC_STOPPING;
1652         wake_up(&d->opd_pre_waitq);
1653
1654         wait_event(thread->t_ctl_waitq, thread->t_flags & SVC_STOPPED);
1655
1656         OBD_FREE_PTR(d->opd_pre);
1657         d->opd_pre = NULL;
1658
1659         EXIT;
1660 }
1661