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