Whamcloud - gitweb
LU-7988 hsm: added coordinator housekeeping flag
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2016, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
51
52 /**
53  * get obj and HSM attributes on a fid
54  * \param mti [IN] context
55  * \param fid [IN] object fid
56  * \param hsm [OUT] HSM meta data
57  * \retval obj or error (-ENOENT if not found)
58  */
59 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
60                                       const struct lu_fid *fid,
61                                       struct md_hsm *hsm)
62 {
63         struct md_attr          *ma;
64         struct mdt_object       *obj;
65         int                      rc;
66         ENTRY;
67
68         ma = &mti->mti_attr;
69         ma->ma_need = MA_HSM;
70         ma->ma_valid = 0;
71
72         /* find object by FID */
73         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
74         if (IS_ERR(obj))
75                 RETURN(obj);
76
77         if (!mdt_object_exists(obj)) {
78                 /* no more object */
79                 mdt_object_put(mti->mti_env, obj);
80                 RETURN(ERR_PTR(-ENOENT));
81         }
82
83         rc = mdt_attr_get_complex(mti, obj, ma);
84         if (rc) {
85                 mdt_object_put(mti->mti_env, obj);
86                 RETURN(ERR_PTR(rc));
87         }
88
89         if (ma->ma_valid & MA_HSM)
90                 *hsm = ma->ma_hsm;
91         else
92                 memset(hsm, 0, sizeof(*hsm));
93         ma->ma_valid = 0;
94         RETURN(obj);
95 }
96
97 void mdt_hsm_dump_hal(int level, const char *prefix,
98                       struct hsm_action_list *hal)
99 {
100         int                      i, sz;
101         struct hsm_action_item  *hai;
102         char                     buf[12];
103
104         CDEBUG(level, "%s: HAL header: version %X count %d compound %#llx"
105                       " archive_id %d flags %#llx\n",
106                prefix, hal->hal_version, hal->hal_count,
107                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
108
109         hai = hai_first(hal);
110         for (i = 0; i < hal->hal_count; i++) {
111                 sz = hai->hai_len - sizeof(*hai);
112                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
113                        " compound/cookie=%#llx/%#llx"
114                        " action=%s extent=%#llx-%#llx gid=%#llx"
115                        " datalen=%d data=[%s]\n",
116                        prefix, i,
117                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
118                        hal->hal_compound_id, hai->hai_cookie,
119                        hsm_copytool_action2name(hai->hai_action),
120                        hai->hai_extent.offset,
121                        hai->hai_extent.length,
122                        hai->hai_gid, sz,
123                        hai_dump_data_field(hai, buf, sizeof(buf)));
124                 hai = hai_next(hai);
125         }
126 }
127
128 /**
129  * data passed to llog_cat_process() callback
130  * to scan requests and take actions
131  */
132 struct hsm_scan_request {
133         int                      hal_sz;
134         int                      hal_used_sz;
135         struct hsm_action_list  *hal;
136 };
137
138 struct hsm_scan_data {
139         struct mdt_thread_info          *mti;
140         char                             fs_name[MTI_NAME_MAXLEN+1];
141         /* are we scanning the logs for housekeeping, or just looking
142          * for new work?
143          */
144         bool                             housekeeping;
145         /* request to be send to agents */
146         int                              max_requests;  /** vector size */
147         int                              request_cnt;   /** used count */
148         struct hsm_scan_request         *request;
149 };
150
151 struct hsm_thread_data {
152         struct mdt_thread_info  *cdt_mti;
153         struct hsm_scan_request *request;
154 };
155 /**
156  *  llog_cat_process() callback, used to:
157  *  - find waiting request and start action
158  *  - purge canceled and done requests
159  * \param env [IN] environment
160  * \param llh [IN] llog handle
161  * \param hdr [IN] llog record
162  * \param data [IN/OUT] cb data = struct hsm_scan_data
163  * \retval 0 success
164  * \retval -ve failure
165  */
166 static int mdt_coordinator_cb(const struct lu_env *env,
167                               struct llog_handle *llh,
168                               struct llog_rec_hdr *hdr,
169                               void *data)
170 {
171         struct llog_agent_req_rec       *larr;
172         struct hsm_scan_data            *hsd;
173         struct hsm_action_item          *hai;
174         struct mdt_device               *mdt;
175         struct coordinator              *cdt;
176         int                              rc;
177         ENTRY;
178
179         hsd = data;
180         mdt = hsd->mti->mti_mdt;
181         cdt = &mdt->mdt_coordinator;
182
183         larr = (struct llog_agent_req_rec *)hdr;
184         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
185         switch (larr->arr_status) {
186         case ARS_WAITING: {
187                 int i;
188                 struct hsm_scan_request *request;
189
190                 /* Are agents full? */
191                 if (atomic_read(&cdt->cdt_request_count) >=
192                     cdt->cdt_max_requests)
193                         break;
194
195                 /* first search whether the request is found in the
196                  * list we have built. */
197                 request = NULL;
198                 for (i = 0; i < hsd->request_cnt; i++) {
199                         if (hsd->request[i].hal->hal_compound_id ==
200                             larr->arr_compound_id) {
201                                 request = &hsd->request[i];
202                                 break;
203                         }
204                 }
205
206                 if (!request) {
207                         struct hsm_action_list *hal;
208
209                         if (hsd->request_cnt == hsd->max_requests) {
210                                 if (!hsd->housekeeping) {
211                                         /* The request array is full,
212                                          * stop here. There might be
213                                          * more known requests that
214                                          * could be merged, but this
215                                          * avoid analyzing too many
216                                          * llogs for minor gains.
217                                          */
218                                         RETURN(LLOG_PROC_BREAK);
219                                 } else {
220                                         /* Unknown request and no more room
221                                          * for a new request. Continue to scan
222                                          * to find other entries for already
223                                          * existing requests.
224                                          */
225                                         RETURN(0);
226                                 }
227                         }
228
229                         request = &hsd->request[hsd->request_cnt];
230
231                         /* allocates hai vector size just needs to be large
232                          * enough */
233                         request->hal_sz =
234                                 sizeof(*request->hal) +
235                                 cfs_size_round(MTI_NAME_MAXLEN+1) +
236                                 2 * cfs_size_round(larr->arr_hai.hai_len);
237                         OBD_ALLOC(hal, request->hal_sz);
238                         if (!hal)
239                                 RETURN(-ENOMEM);
240                         hal->hal_version = HAL_VERSION;
241                         strlcpy(hal->hal_fsname, hsd->fs_name,
242                                 MTI_NAME_MAXLEN + 1);
243                         hal->hal_compound_id = larr->arr_compound_id;
244                         hal->hal_archive_id = larr->arr_archive_id;
245                         hal->hal_flags = larr->arr_flags;
246                         hal->hal_count = 0;
247                         request->hal_used_sz = hal_size(hal);
248                         request->hal = hal;
249                         hsd->request_cnt++;
250                         hai = hai_first(hal);
251                 } else {
252                         /* request is known */
253                         /* we check if record archive num is the same as the
254                          * known request, if not we will serve it in multiple
255                          * time because we do not know if the agent can serve
256                          * multiple backend
257                          * a use case is a compound made of multiple restore
258                          * where the files are not archived in the same backend
259                          */
260                         if (larr->arr_archive_id !=
261                             request->hal->hal_archive_id)
262                                 RETURN(0);
263
264                         if (request->hal_sz <
265                             request->hal_used_sz +
266                             cfs_size_round(larr->arr_hai.hai_len)) {
267                                 /* Not enough room, need an extension */
268                                 void *hal_buffer;
269                                 int sz;
270
271                                 sz = 2 * request->hal_sz;
272                                 OBD_ALLOC(hal_buffer, sz);
273                                 if (!hal_buffer)
274                                         RETURN(-ENOMEM);
275                                 memcpy(hal_buffer, request->hal,
276                                        request->hal_used_sz);
277                                 OBD_FREE(request->hal,
278                                          request->hal_sz);
279                                 request->hal = hal_buffer;
280                                 request->hal_sz = sz;
281                         }
282                         hai = hai_first(request->hal);
283                         for (i = 0; i < request->hal->hal_count; i++)
284                                 hai = hai_next(hai);
285                 }
286                 memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
287                 hai->hai_cookie = larr->arr_hai.hai_cookie;
288                 hai->hai_gid = larr->arr_hai.hai_gid;
289
290                 request->hal_used_sz += cfs_size_round(hai->hai_len);
291                 request->hal->hal_count++;
292
293                 if (hai->hai_action != HSMA_CANCEL)
294                         cdt_agent_record_hash_add(cdt, hai->hai_cookie,
295                                                   llh->lgh_hdr->llh_cat_idx,
296                                                   hdr->lrh_index);
297                 break;
298         }
299         case ARS_STARTED: {
300                 struct hsm_progress_kernel pgs;
301                 struct cdt_agent_req *car;
302                 cfs_time_t now = cfs_time_current_sec();
303                 cfs_time_t last;
304
305                 if (!hsd->housekeeping)
306                         break;
307
308                 /* we search for a running request
309                  * error may happen if coordinator crashes or stopped
310                  * with running request
311                  */
312                 car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie);
313                 if (car == NULL) {
314                         last = larr->arr_req_change;
315                 } else {
316                         last = car->car_req_update;
317                         mdt_cdt_put_request(car);
318                 }
319
320                 /* test if request too long, if yes cancel it
321                  * the same way the copy tool acknowledge a cancel request */
322                 if (now <= last + cdt->cdt_active_req_timeout)
323                         RETURN(0);
324
325                 dump_llog_agent_req_rec("request timed out, start cleaning",
326                                         larr);
327                 /* a too old cancel request just needs to be removed
328                  * this can happen, if copy tool does not support
329                  * cancel for other requests, we have to remove the
330                  * running request and notify the copytool */
331                 pgs.hpk_fid = larr->arr_hai.hai_fid;
332                 pgs.hpk_cookie = larr->arr_hai.hai_cookie;
333                 pgs.hpk_extent = larr->arr_hai.hai_extent;
334                 pgs.hpk_flags = HP_FLAG_COMPLETED;
335                 pgs.hpk_errval = ENOSYS;
336                 pgs.hpk_data_version = 0;
337
338                 /* update request state, but do not record in llog, to
339                  * avoid deadlock on cdt_llog_lock */
340                 rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
341                 if (rc)
342                         CERROR("%s: cannot cleanup timed out request: "
343                                DFID" for cookie %#llx action=%s\n",
344                                mdt_obd_name(mdt),
345                                PFID(&pgs.hpk_fid), pgs.hpk_cookie,
346                                hsm_copytool_action2name(
347                                        larr->arr_hai.hai_action));
348
349                 if (rc == -ENOENT) {
350                         /* The request no longer exists, forget
351                          * about it, and do not send a cancel request
352                          * to the client, for which an error will be
353                          * sent back, leading to an endless cycle of
354                          * cancellation. */
355                         cdt_agent_record_hash_del(cdt,
356                                                   larr->arr_hai.hai_cookie);
357                         RETURN(LLOG_DEL_RECORD);
358                 }
359
360                 /* XXX A cancel request cannot be cancelled. */
361                 if (larr->arr_hai.hai_action == HSMA_CANCEL)
362                         RETURN(0);
363
364                 larr->arr_status = ARS_CANCELED;
365                 larr->arr_req_change = now;
366                 rc = llog_write(hsd->mti->mti_env, llh, hdr, hdr->lrh_index);
367                 if (rc < 0)
368                         CERROR("%s: cannot update agent log: rc = %d\n",
369                                mdt_obd_name(mdt), rc);
370                 break;
371         }
372         case ARS_FAILED:
373         case ARS_CANCELED:
374         case ARS_SUCCEED:
375                 if (!hsd->housekeeping)
376                         break;
377
378                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
379                     cfs_time_current_sec()) {
380                         cdt_agent_record_hash_del(cdt,
381                                                   larr->arr_hai.hai_cookie);
382                         RETURN(LLOG_DEL_RECORD);
383                 }
384                 break;
385         }
386         RETURN(0);
387 }
388
389 /**
390  * create /proc entries for coordinator
391  * \param mdt [IN]
392  * \retval 0 success
393  * \retval -ve failure
394  */
395 int hsm_cdt_procfs_init(struct mdt_device *mdt)
396 {
397         struct coordinator      *cdt = &mdt->mdt_coordinator;
398         int                      rc = 0;
399         ENTRY;
400
401         /* init /proc entries, failure is not critical */
402         cdt->cdt_proc_dir = lprocfs_register("hsm",
403                                              mdt2obd_dev(mdt)->obd_proc_entry,
404                                              lprocfs_mdt_hsm_vars, mdt);
405         if (IS_ERR(cdt->cdt_proc_dir)) {
406                 rc = PTR_ERR(cdt->cdt_proc_dir);
407                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
408                        " rc=%d\n", mdt_obd_name(mdt), rc);
409                 cdt->cdt_proc_dir = NULL;
410                 RETURN(rc);
411         }
412
413         RETURN(0);
414 }
415
416 /**
417  * remove /proc entries for coordinator
418  * \param mdt [IN]
419  */
420 void hsm_cdt_procfs_fini(struct mdt_device *mdt)
421 {
422         struct coordinator *cdt = &mdt->mdt_coordinator;
423
424         if (cdt->cdt_proc_dir != NULL)
425                 lprocfs_remove(&cdt->cdt_proc_dir);
426 }
427
428 /**
429  * get vector of hsm cdt /proc vars
430  * \param none
431  * \retval var vector
432  */
433 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
434 {
435         return lprocfs_mdt_hsm_vars;
436 }
437
438 /* Release the ressource used by the coordinator. Called when the
439  * coordinator is stopping. */
440 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
441 {
442         struct coordinator              *cdt = &mdt->mdt_coordinator;
443         struct cdt_agent_req            *car, *tmp1;
444         struct hsm_agent                *ha, *tmp2;
445         struct cdt_restore_handle       *crh, *tmp3;
446         struct mdt_thread_info          *cdt_mti;
447
448         /* start cleaning */
449         down_write(&cdt->cdt_request_lock);
450         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
451                                  car_request_list) {
452                 cfs_hash_del(cdt->cdt_request_cookie_hash,
453                              &car->car_hai->hai_cookie,
454                              &car->car_cookie_hash);
455                 list_del(&car->car_request_list);
456                 mdt_cdt_put_request(car);
457         }
458         up_write(&cdt->cdt_request_lock);
459
460         down_write(&cdt->cdt_agent_lock);
461         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
462                 list_del(&ha->ha_list);
463                 OBD_FREE_PTR(ha);
464         }
465         up_write(&cdt->cdt_agent_lock);
466
467         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
468         mutex_lock(&cdt->cdt_restore_lock);
469         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_hdl, crh_list) {
470                 list_del(&crh->crh_list);
471                 /* give back layout lock */
472                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
473                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
474         }
475         mutex_unlock(&cdt->cdt_restore_lock);
476 }
477
478 /*
479  * Coordinator state transition table, indexed on enum cdt_states, taking
480  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
481  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
482  */
483 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
484         /* from -> to:    stopped init   running disable stopping */
485         /* stopped */   { true,   true,  false,  false,  false },
486         /* init */      { true,   false, true,   false,  false },
487         /* running */   { false,  false, true,   true,   true },
488         /* disable */   { false,  false, true,   true,   true },
489         /* stopping */  { true,   false, false,  false,  false }
490 };
491
492 /**
493  * Change coordinator thread state
494  * Some combinations are not valid, so catch them here.
495  *
496  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
497  * the transition was not possible.
498  */
499 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state,
500                          enum cdt_states *old_state)
501 {
502         int rc;
503         enum cdt_states state;
504
505         spin_lock(&cdt->cdt_state_lock);
506
507         state = cdt->cdt_state;
508
509         if (cdt_transition[state][new_state]) {
510                 cdt->cdt_state = new_state;
511                 spin_unlock(&cdt->cdt_state_lock);
512                 if (old_state)
513                         *old_state = state;
514                 rc = 0;
515         } else {
516                 spin_unlock(&cdt->cdt_state_lock);
517                 CDEBUG(D_HSM,
518                        "unexpected coordinator transition, from=%s, to=%s\n",
519                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
520                 rc = -EINVAL;
521         }
522
523         return rc;
524 }
525
526 /**
527  * coordinator thread
528  * \param data [IN] obd device
529  * \retval 0 success
530  * \retval -ve failure
531  */
532 static int mdt_coordinator(void *data)
533 {
534         struct hsm_thread_data  *thread_data = data;
535         struct mdt_thread_info  *mti = thread_data->cdt_mti;
536         struct mdt_device       *mdt = mti->mti_mdt;
537         struct coordinator      *cdt = &mdt->mdt_coordinator;
538         struct hsm_scan_data     hsd = { NULL };
539         time64_t                 wait_event_time = 1 * HZ;
540         time64_t                 last_housekeeping = 0;
541         int                      rc = 0;
542         int                      request_sz;
543         ENTRY;
544
545         /* set up hsd->request and max_requests */
546         hsd.max_requests = cdt->cdt_max_requests;
547         request_sz = hsd.max_requests * sizeof(*hsd.request);
548         hsd.request = thread_data->request;
549
550         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
551                mdt_obd_name(mdt), current_pid());
552
553         hsd.mti = mti;
554         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
555
556         set_cdt_state(cdt, CDT_RUNNING, NULL);
557
558         /* Inform mdt_hsm_cdt_start(). */
559         wake_up_all(&cdt->cdt_waitq);
560
561         while (1) {
562                 int i;
563
564                 /* Limit execution of the expensive requests traversal
565                  * to at most every "wait_event_time" jiffies. This prevents
566                  * repeatedly locking/unlocking the catalog for each request
567                  * and preventing other HSM operations from happening */
568                 wait_event_interruptible_timeout(cdt->cdt_waitq,
569                                                  kthread_should_stop(),
570                                                  wait_event_time);
571
572                 CDEBUG(D_HSM, "coordinator resumes\n");
573
574                 if (kthread_should_stop()) {
575                         CDEBUG(D_HSM, "Coordinator stops\n");
576                         rc = 0;
577                         break;
578                 }
579
580                 /* if coordinator is suspended continue to wait */
581                 if (cdt->cdt_state == CDT_DISABLE) {
582                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
583                         continue;
584                 }
585
586                 /* If no event, and no housekeeping to do, continue to
587                  * wait. */
588                 if (last_housekeeping + cdt->cdt_loop_period <=
589                     get_seconds()) {
590                         last_housekeeping = get_seconds();
591                         hsd.housekeeping = true;
592                 } else if (cdt->cdt_event) {
593                         hsd.housekeeping = false;
594                 } else {
595                         continue;
596                 }
597
598                 cdt->cdt_event = false;
599
600                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
601
602                 if (hsd.max_requests != cdt->cdt_max_requests) {
603                         /* cdt_max_requests has changed,
604                          * we need to allocate a new buffer
605                          */
606                         struct hsm_scan_request *tmp = NULL;
607                         int max_requests = cdt->cdt_max_requests;
608                         OBD_ALLOC_LARGE(tmp, max_requests *
609                                         sizeof(struct hsm_scan_request));
610                         if (!tmp) {
611                                 CERROR("Failed to resize request buffer, "
612                                        "keeping it at %d\n",
613                                        hsd.max_requests);
614                                 cdt->cdt_max_requests = hsd.max_requests;
615                         } else {
616                                 OBD_FREE_LARGE(hsd.request, request_sz);
617                                 hsd.max_requests = max_requests;
618                                 request_sz = hsd.max_requests *
619                                         sizeof(struct hsm_scan_request);
620                                 hsd.request = tmp;
621                         }
622                 }
623
624                 hsd.request_cnt = 0;
625
626                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
627                                       &hsd, 0, 0, WRITE);
628                 if (rc < 0)
629                         goto clean_cb_alloc;
630
631                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
632
633                 if (list_empty(&cdt->cdt_agents)) {
634                         CDEBUG(D_HSM, "no agent available, "
635                                       "coordinator sleeps\n");
636                         goto clean_cb_alloc;
637                 }
638
639                 /* here hsd contains a list of requests to be started */
640                 for (i = 0; i < hsd.request_cnt; i++) {
641                         struct hsm_scan_request *request = &hsd.request[i];
642                         struct hsm_action_list  *hal = request->hal;
643                         struct hsm_action_item  *hai;
644                         __u64                   *cookies;
645                         int                      sz, j;
646                         enum agent_req_status    status;
647
648                         /* still room for work ? */
649                         if (atomic_read(&cdt->cdt_request_count) >=
650                             cdt->cdt_max_requests)
651                                 break;
652
653                         rc = mdt_hsm_agent_send(mti, hal, 0);
654                         /* if failure, we suppose it is temporary
655                          * if the copy tool failed to do the request
656                          * it has to use hsm_progress
657                          */
658                         status = (rc ? ARS_WAITING : ARS_STARTED);
659
660                         /* set up cookie vector to set records status
661                          * after copy tools start or failed
662                          */
663                         sz = hal->hal_count * sizeof(__u64);
664                         OBD_ALLOC(cookies, sz);
665                         if (cookies == NULL)
666                                 continue;
667
668                         hai = hai_first(hal);
669                         for (j = 0; j < hal->hal_count; j++) {
670                                 cookies[j] = hai->hai_cookie;
671                                 hai = hai_next(hai);
672                         }
673
674                         rc = mdt_agent_record_update(mti->mti_env, mdt, cookies,
675                                                      hal->hal_count, status);
676                         if (rc)
677                                 CERROR("%s: mdt_agent_record_update() failed, "
678                                        "rc=%d, cannot update status to %s "
679                                        "for %d cookies\n",
680                                        mdt_obd_name(mdt), rc,
681                                        agent_req_status2name(status),
682                                        hal->hal_count);
683
684                         OBD_FREE(cookies, sz);
685                 }
686 clean_cb_alloc:
687                 /* free hal allocated by callback */
688                 for (i = 0; i < hsd.request_cnt; i++) {
689                         struct hsm_scan_request *request = &hsd.request[i];
690
691                         OBD_FREE(request->hal, request->hal_sz);
692                 }
693         }
694
695         if (hsd.request)
696                 OBD_FREE_LARGE(hsd.request, request_sz);
697
698         mdt_hsm_cdt_cleanup(mdt);
699
700         if (rc != 0)
701                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
702                        mdt_obd_name(mdt), current_pid(), rc);
703         else
704                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
705                               " no error\n",
706                        mdt_obd_name(mdt), current_pid());
707
708         RETURN(rc);
709 }
710
711 /**
712  * lookup a restore handle by FID
713  * caller needs to hold cdt_restore_lock
714  * \param cdt [IN] coordinator
715  * \param fid [IN] FID
716  * \retval cdt_restore_handle found
717  * \retval NULL not found
718  */
719 struct cdt_restore_handle *mdt_hsm_restore_hdl_find(struct coordinator *cdt,
720                                                        const struct lu_fid *fid)
721 {
722         struct cdt_restore_handle       *crh;
723         ENTRY;
724
725         list_for_each_entry(crh, &cdt->cdt_restore_hdl, crh_list) {
726                 if (lu_fid_eq(&crh->crh_fid, fid))
727                         RETURN(crh);
728         }
729         RETURN(NULL);
730 }
731
732 /**
733  * data passed to llog_cat_process() callback
734  * to scan requests and take actions
735  */
736 struct hsm_restore_data {
737         struct mdt_thread_info  *hrd_mti;
738 };
739
740 /**
741  *  llog_cat_process() callback, used to:
742  *  - find restore request and allocate the restore handle
743  * \param env [IN] environment
744  * \param llh [IN] llog handle
745  * \param hdr [IN] llog record
746  * \param data [IN/OUT] cb data = struct hsm_restore_data
747  * \retval 0 success
748  * \retval -ve failure
749  */
750 static int hsm_restore_cb(const struct lu_env *env,
751                           struct llog_handle *llh,
752                           struct llog_rec_hdr *hdr, void *data)
753 {
754         struct llog_agent_req_rec       *larr;
755         struct hsm_restore_data         *hrd;
756         struct cdt_restore_handle       *crh;
757         struct hsm_action_item          *hai;
758         struct mdt_thread_info          *mti;
759         struct coordinator              *cdt;
760         struct mdt_object               *child;
761         int rc;
762         ENTRY;
763
764         hrd = data;
765         mti = hrd->hrd_mti;
766         cdt = &mti->mti_mdt->mdt_coordinator;
767
768         larr = (struct llog_agent_req_rec *)hdr;
769         hai = &larr->arr_hai;
770         if (hai->hai_cookie > cdt->cdt_last_cookie)
771                 /* update the cookie to avoid collision */
772                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
773
774         if (hai->hai_action != HSMA_RESTORE ||
775             agent_req_in_final_state(larr->arr_status))
776                 RETURN(0);
777
778         /* restore request not in a final state */
779
780         /* force replay of restore requests left in started state from previous
781          * CDT context, to be canceled later if finally found to be incompatible
782          * when being re-started */
783         if (larr->arr_status == ARS_STARTED) {
784                 larr->arr_status = ARS_WAITING;
785                 larr->arr_req_change = cfs_time_current_sec();
786                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
787                 if (rc != 0)
788                         GOTO(out, rc);
789         }
790
791         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
792         if (crh == NULL)
793                 RETURN(-ENOMEM);
794
795         crh->crh_fid = hai->hai_fid;
796         /* in V1 all file is restored
797         crh->extent.start = hai->hai_extent.offset;
798         crh->extent.end = hai->hai_extent.offset + hai->hai_extent.length;
799         */
800         crh->crh_extent.start = 0;
801         crh->crh_extent.end = hai->hai_extent.length;
802         /* get the layout lock */
803         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
804         child = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
805                                      MDS_INODELOCK_LAYOUT);
806         if (IS_ERR(child))
807                 GOTO(out, rc = PTR_ERR(child));
808
809         rc = 0;
810         /* we choose to not keep a reference
811          * on the object during the restore time which can be very long */
812         mdt_object_put(mti->mti_env, child);
813
814         mutex_lock(&cdt->cdt_restore_lock);
815         list_add_tail(&crh->crh_list, &cdt->cdt_restore_hdl);
816         mutex_unlock(&cdt->cdt_restore_lock);
817
818 out:
819         RETURN(rc);
820 }
821
822 /**
823  * restore coordinator state at startup
824  * the goal is to take a layout lock for each registered restore request
825  * \param mti [IN] context
826  */
827 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
828 {
829         struct hsm_restore_data  hrd;
830         int                      rc;
831         ENTRY;
832
833         hrd.hrd_mti = mti;
834
835         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
836                               0, 0, WRITE);
837
838         RETURN(rc);
839 }
840
841 static int hsm_init_ucred(struct lu_ucred *uc)
842 {
843         ENTRY;
844
845         uc->uc_valid = UCRED_OLD;
846         uc->uc_o_uid = 0;
847         uc->uc_o_gid = 0;
848         uc->uc_o_fsuid = 0;
849         uc->uc_o_fsgid = 0;
850         uc->uc_uid = 0;
851         uc->uc_gid = 0;
852         uc->uc_fsuid = 0;
853         uc->uc_fsgid = 0;
854         uc->uc_suppgids[0] = -1;
855         uc->uc_suppgids[1] = -1;
856         uc->uc_cap = CFS_CAP_FS_MASK;
857         uc->uc_umask = 0777;
858         uc->uc_ginfo = NULL;
859         uc->uc_identity = NULL;
860
861         RETURN(0);
862 }
863
864 /**
865  * initialize coordinator struct
866  * \param mdt [IN] device
867  * \retval 0 success
868  * \retval -ve failure
869  */
870 int mdt_hsm_cdt_init(struct mdt_device *mdt)
871 {
872         struct coordinator      *cdt = &mdt->mdt_coordinator;
873         struct mdt_thread_info  *cdt_mti = NULL;
874         int                      rc;
875         ENTRY;
876
877         init_waitqueue_head(&cdt->cdt_waitq);
878         init_rwsem(&cdt->cdt_llog_lock);
879         init_rwsem(&cdt->cdt_agent_lock);
880         init_rwsem(&cdt->cdt_request_lock);
881         mutex_init(&cdt->cdt_restore_lock);
882         spin_lock_init(&cdt->cdt_state_lock);
883         set_cdt_state(cdt, CDT_STOPPED, NULL);
884
885         INIT_LIST_HEAD(&cdt->cdt_request_list);
886         INIT_LIST_HEAD(&cdt->cdt_agents);
887         INIT_LIST_HEAD(&cdt->cdt_restore_hdl);
888
889         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
890                                                        CFS_HASH_BITS_MIN,
891                                                        CFS_HASH_BITS_MAX,
892                                                        CFS_HASH_BKT_BITS,
893                                                        0 /* extra bytes */,
894                                                        CFS_HASH_MIN_THETA,
895                                                        CFS_HASH_MAX_THETA,
896                                                 &cdt_request_cookie_hash_ops,
897                                                        CFS_HASH_DEFAULT);
898         if (cdt->cdt_request_cookie_hash == NULL)
899                 RETURN(-ENOMEM);
900
901         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
902                                                      CFS_HASH_BITS_MIN,
903                                                      CFS_HASH_BITS_MAX,
904                                                      CFS_HASH_BKT_BITS,
905                                                      0 /* extra bytes */,
906                                                      CFS_HASH_MIN_THETA,
907                                                      CFS_HASH_MAX_THETA,
908                                                      &cdt_agent_record_hash_ops,
909                                                      CFS_HASH_DEFAULT);
910         if (cdt->cdt_agent_record_hash == NULL)
911                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
912
913         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
914         if (rc < 0)
915                 GOTO(out_agent_record_hash, rc);
916
917         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
918         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
919         if (rc < 0)
920                 GOTO(out_env, rc);
921
922         lu_context_enter(&cdt->cdt_session);
923         cdt->cdt_env.le_ses = &cdt->cdt_session;
924
925         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
926         LASSERT(cdt_mti != NULL);
927
928         cdt_mti->mti_env = &cdt->cdt_env;
929         cdt_mti->mti_mdt = mdt;
930
931         hsm_init_ucred(mdt_ucred(cdt_mti));
932
933         /* default values for /proc tunnables
934          * can be override by MGS conf */
935         cdt->cdt_default_archive_id = 1;
936         cdt->cdt_grace_delay = 60;
937         cdt->cdt_loop_period = 10;
938         cdt->cdt_max_requests = 3;
939         cdt->cdt_policy = CDT_DEFAULT_POLICY;
940         cdt->cdt_active_req_timeout = 3600;
941
942         /* Initialize cdt_compound_id here to allow its usage for
943          * delayed requests from RAoLU policy */
944         atomic_set(&cdt->cdt_compound_id, cfs_time_current_sec());
945
946         /* by default do not remove archives on last unlink */
947         cdt->cdt_remove_archive_on_last_unlink = false;
948
949         RETURN(0);
950
951 out_env:
952         lu_env_fini(&cdt->cdt_env);
953 out_agent_record_hash:
954         cfs_hash_putref(cdt->cdt_agent_record_hash);
955         cdt->cdt_agent_record_hash = NULL;
956 out_request_cookie_hash:
957         cfs_hash_putref(cdt->cdt_request_cookie_hash);
958         cdt->cdt_request_cookie_hash = NULL;
959
960         return rc;
961 }
962
963 /**
964  * free a coordinator thread
965  * \param mdt [IN] device
966  */
967 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
968 {
969         struct coordinator *cdt = &mdt->mdt_coordinator;
970         ENTRY;
971
972         lu_context_exit(cdt->cdt_env.le_ses);
973         lu_context_fini(cdt->cdt_env.le_ses);
974
975         lu_env_fini(&cdt->cdt_env);
976
977         cfs_hash_putref(cdt->cdt_agent_record_hash);
978         cdt->cdt_agent_record_hash = NULL;
979
980         cfs_hash_putref(cdt->cdt_request_cookie_hash);
981         cdt->cdt_request_cookie_hash = NULL;
982
983         RETURN(0);
984 }
985
986 /**
987  * start a coordinator thread
988  * \param mdt [IN] device
989  * \retval 0 success
990  * \retval -ve failure
991  */
992 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
993 {
994         struct coordinator      *cdt = &mdt->mdt_coordinator;
995         int                      rc;
996         void                    *ptr;
997         struct task_struct      *task;
998         int                      request_sz;
999         struct hsm_thread_data   thread_data;
1000         ENTRY;
1001
1002         /* functions defined but not yet used
1003          * this avoid compilation warning
1004          */
1005         ptr = dump_requests;
1006
1007         rc = set_cdt_state(cdt, CDT_INIT, NULL);
1008         if (rc) {
1009                 CERROR("%s: Coordinator already started or stopping\n",
1010                        mdt_obd_name(mdt));
1011                 RETURN(-EALREADY);
1012         }
1013
1014         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
1015         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1016
1017         /* just need to be larger than previous one */
1018         /* cdt_last_cookie is protected by cdt_llog_lock */
1019         cdt->cdt_last_cookie = cfs_time_current_sec();
1020         atomic_set(&cdt->cdt_request_count, 0);
1021         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1022         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1023         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1024
1025         /* to avoid deadlock when start is made through /proc
1026          * /proc entries are created by the coordinator thread */
1027
1028         /* set up list of started restore requests */
1029         thread_data.cdt_mti =
1030                 lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1031         rc = mdt_hsm_pending_restore(thread_data.cdt_mti);
1032         if (rc)
1033                 CERROR("%s: cannot take the layout locks needed"
1034                        " for registered restore: %d\n",
1035                        mdt_obd_name(mdt), rc);
1036
1037         if (mdt->mdt_bottom->dd_rdonly)
1038                 RETURN(0);
1039
1040         /* Allocate the initial hsd.request[] vector*/
1041         request_sz = cdt->cdt_max_requests * sizeof(struct hsm_scan_request);
1042         OBD_ALLOC_LARGE(thread_data.request, request_sz);
1043         if (!thread_data.request) {
1044                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1045                 RETURN(-ENOMEM);
1046         }
1047
1048         task = kthread_run(mdt_coordinator, &thread_data, "hsm_cdtr");
1049         if (IS_ERR(task)) {
1050                 rc = PTR_ERR(task);
1051                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1052                 OBD_FREE(thread_data.request, request_sz);
1053                 CERROR("%s: error starting coordinator thread: %d\n",
1054                        mdt_obd_name(mdt), rc);
1055         } else {
1056                 cdt->cdt_task = task;
1057                 wait_event(cdt->cdt_waitq,
1058                            cdt->cdt_state != CDT_INIT);
1059                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1060                        mdt_obd_name(mdt));
1061                 rc = 0;
1062         }
1063
1064         RETURN(rc);
1065 }
1066
1067 /**
1068  * stop a coordinator thread
1069  * \param mdt [IN] device
1070  */
1071 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1072 {
1073         struct coordinator *cdt = &mdt->mdt_coordinator;
1074         int rc;
1075
1076         ENTRY;
1077         /* stop coordinator thread */
1078         rc = set_cdt_state(cdt, CDT_STOPPING, NULL);
1079         if (rc == 0) {
1080                 kthread_stop(cdt->cdt_task);
1081                 cdt->cdt_task = NULL;
1082                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1083         }
1084
1085         RETURN(rc);
1086 }
1087
1088 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1089                               const struct lu_fid *fid,
1090                               u32 archive_id)
1091 {
1092         struct mdt_object *obj;
1093         struct md_hsm mh;
1094         int rc;
1095
1096         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1097         if (IS_ERR(obj))
1098                 GOTO(out, rc = PTR_ERR(obj));
1099
1100         if (mh.mh_flags & HS_EXISTS &&
1101             mh.mh_arch_id == archive_id)
1102                 GOTO(out_obj, rc = 0);
1103
1104         mh.mh_flags |= HS_EXISTS;
1105         mh.mh_arch_id = archive_id;
1106         rc = mdt_hsm_attr_set(mti, obj, &mh);
1107
1108 out_obj:
1109         mdt_object_put(mti->mti_env, obj);
1110 out:
1111         return rc;
1112 }
1113
1114 /**
1115  * register all requests from an hal in the memory list
1116  * \param mti [IN] context
1117  * \param hal [IN] request
1118  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1119  *  which is running the CT
1120  * \retval 0 success
1121  * \retval -ve failure
1122  */
1123 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1124                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1125 {
1126         struct mdt_device       *mdt = mti->mti_mdt;
1127         struct coordinator      *cdt = &mdt->mdt_coordinator;
1128         struct hsm_action_item  *hai;
1129         int                      rc = 0, i;
1130         ENTRY;
1131
1132         /* register request in memory list */
1133         hai = hai_first(hal);
1134         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1135                 struct cdt_agent_req *car;
1136
1137                 /* in case of a cancel request, we first mark the ondisk
1138                  * record of the request we want to stop as canceled
1139                  * this does not change the cancel record
1140                  * it will be done when updating the request status
1141                  */
1142                 if (hai->hai_action == HSMA_CANCEL) {
1143                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1144                                                      &hai->hai_cookie,
1145                                                      1, ARS_CANCELED);
1146                         if (rc) {
1147                                 CERROR("%s: mdt_agent_record_update() failed, "
1148                                        "rc=%d, cannot update status to %s "
1149                                        "for cookie %#llx\n",
1150                                        mdt_obd_name(mdt), rc,
1151                                        agent_req_status2name(ARS_CANCELED),
1152                                        hai->hai_cookie);
1153                                 GOTO(out, rc);
1154                         }
1155
1156                         /* find the running request to set it canceled */
1157                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1158                         if (car != NULL) {
1159                                 car->car_canceled = 1;
1160                                 /* uuid has to be changed to the one running the
1161                                 * request to cancel */
1162                                 *uuid = car->car_uuid;
1163                                 mdt_cdt_put_request(car);
1164                         }
1165                         /* no need to memorize cancel request
1166                          * this also avoid a deadlock when we receive
1167                          * a purge all requests command
1168                          */
1169                         continue;
1170                 }
1171
1172                 if (hai->hai_action == HSMA_ARCHIVE) {
1173                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1174                                                 hal->hal_archive_id);
1175                         if (rc == -ENOENT)
1176                                 continue;
1177                         else if (rc < 0)
1178                                 GOTO(out, rc);
1179                 }
1180
1181                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1182                                             hal->hal_archive_id, hal->hal_flags,
1183                                             uuid, hai);
1184                 if (IS_ERR(car))
1185                         GOTO(out, rc = PTR_ERR(car));
1186
1187                 rc = mdt_cdt_add_request(cdt, car);
1188                 if (rc != 0)
1189                         mdt_cdt_free_request(car);
1190         }
1191 out:
1192         RETURN(rc);
1193 }
1194
1195 /**
1196  * swap layouts between 2 fids
1197  * \param mti [IN] context
1198  * \param obj [IN]
1199  * \param dfid [IN]
1200  * \param mh_common [IN] MD HSM
1201  */
1202 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1203                             struct mdt_object *obj, const struct lu_fid *dfid,
1204                             struct md_hsm *mh_common)
1205 {
1206         struct mdt_object       *dobj;
1207         struct mdt_lock_handle  *dlh;
1208         int                      rc;
1209         ENTRY;
1210
1211         if (!mdt_object_exists(obj))
1212                 GOTO(out, rc = -ENOENT);
1213
1214         /* we already have layout lock on obj so take only
1215          * on dfid */
1216         dlh = &mti->mti_lh[MDT_LH_OLD];
1217         mdt_lock_reg_init(dlh, LCK_EX);
1218         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1219         if (IS_ERR(dobj))
1220                 GOTO(out, rc = PTR_ERR(dobj));
1221
1222         /* if copy tool closes the volatile before sending the final
1223          * progress through llapi_hsm_copy_end(), all the objects
1224          * are removed and mdd_swap_layout LBUG */
1225         if (!mdt_object_exists(dobj)) {
1226                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1227                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1228                 GOTO(out_dobj, rc = -ENOENT);
1229         }
1230         /* Since we only handle restores here, unconditionally use
1231          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1232          * be preserved in case of failure during swap_layout and not
1233          * leave a file in an intermediate but incoherent state.
1234          * But need to setup HSM xattr of data FID before, reuse
1235          * mti and mh presets for FID in hsm_cdt_request_completed(),
1236          * only need to clear RELEASED and DIRTY.
1237          */
1238         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1239         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1240         if (rc == 0)
1241                 rc = mo_swap_layouts(mti->mti_env,
1242                                      mdt_object_child(obj),
1243                                      mdt_object_child(dobj),
1244                                      SWAP_LAYOUTS_MDS_HSM);
1245
1246 out_dobj:
1247         mdt_object_unlock_put(mti, dobj, dlh, 1);
1248 out:
1249         RETURN(rc);
1250 }
1251
1252 /**
1253  * update status of a completed request
1254  * \param mti [IN] context
1255  * \param pgs [IN] progress of the copy tool
1256  * \param update_record [IN] update llog record
1257  * \retval 0 success
1258  * \retval -ve failure
1259  */
1260 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1261                                      struct hsm_progress_kernel *pgs,
1262                                      const struct cdt_agent_req *car,
1263                                      enum agent_req_status *status)
1264 {
1265         const struct lu_env     *env = mti->mti_env;
1266         struct mdt_device       *mdt = mti->mti_mdt;
1267         struct coordinator      *cdt = &mdt->mdt_coordinator;
1268         struct mdt_object       *obj = NULL;
1269         int                      cl_flags = 0, rc = 0;
1270         struct md_hsm            mh;
1271         bool                     is_mh_changed;
1272         bool                     need_changelog = true;
1273         ENTRY;
1274
1275         /* default is to retry */
1276         *status = ARS_WAITING;
1277
1278         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1279          * if error/removed continue anyway to get correct reporting done */
1280         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1281         /* we will update MD HSM only if needed */
1282         is_mh_changed = false;
1283
1284         /* no need to change mh->mh_arch_id
1285          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1286          */
1287         if (pgs->hpk_errval != 0) {
1288                 switch (pgs->hpk_errval) {
1289                 case ENOSYS:
1290                         /* the copy tool does not support cancel
1291                          * so the cancel request is failed
1292                          * As we cannot distinguish a cancel progress
1293                          * from another action progress (they have the
1294                          * same cookie), we suppose here the CT returns
1295                          * ENOSYS only if does not support cancel
1296                          */
1297                         /* this can also happen when cdt calls it to
1298                          * for a timed out request */
1299                         *status = ARS_FAILED;
1300                         /* to have a cancel event in changelog */
1301                         pgs->hpk_errval = ECANCELED;
1302                         break;
1303                 case ECANCELED:
1304                         /* the request record has already been set to
1305                          * ARS_CANCELED, this set the cancel request
1306                          * to ARS_SUCCEED */
1307                         *status = ARS_SUCCEED;
1308                         break;
1309                 default:
1310                         /* retry only if current policy or requested, and
1311                          * object is not on error/removed */
1312                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1313                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1314                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1315                         break;
1316                 }
1317
1318                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1319                         CERROR("%s: Request %#llx on "DFID
1320                                " failed, error code %d too large\n",
1321                                mdt_obd_name(mdt),
1322                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1323                                pgs->hpk_errval);
1324                         hsm_set_cl_error(&cl_flags,
1325                                          CLF_HSM_ERROVERFLOW);
1326                         rc = -EINVAL;
1327                 } else {
1328                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1329                 }
1330
1331                 switch (car->car_hai->hai_action) {
1332                 case HSMA_ARCHIVE:
1333                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1334                         break;
1335                 case HSMA_RESTORE:
1336                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1337                         break;
1338                 case HSMA_REMOVE:
1339                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1340                         break;
1341                 case HSMA_CANCEL:
1342                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1343                         CERROR("%s: Failed request %#llx on "DFID
1344                                " cannot be a CANCEL\n",
1345                                mdt_obd_name(mdt),
1346                                pgs->hpk_cookie,
1347                                PFID(&pgs->hpk_fid));
1348                         break;
1349                 default:
1350                         CERROR("%s: Failed request %#llx on "DFID
1351                                " %d is an unknown action\n",
1352                                mdt_obd_name(mdt),
1353                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1354                                car->car_hai->hai_action);
1355                         rc = -EINVAL;
1356                         break;
1357                 }
1358         } else {
1359                 *status = ARS_SUCCEED;
1360                 switch (car->car_hai->hai_action) {
1361                 case HSMA_ARCHIVE:
1362                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1363                         /* set ARCHIVE keep EXIST and clear LOST and
1364                          * DIRTY */
1365                         mh.mh_arch_ver = pgs->hpk_data_version;
1366                         mh.mh_flags |= HS_ARCHIVED;
1367                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1368                         is_mh_changed = true;
1369                         break;
1370                 case HSMA_RESTORE:
1371                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1372
1373                         /* do not clear RELEASED and DIRTY here
1374                          * this will occur in hsm_swap_layouts()
1375                          */
1376
1377                         /* Restoring has changed the file version on
1378                          * disk. */
1379                         mh.mh_arch_ver = pgs->hpk_data_version;
1380                         is_mh_changed = true;
1381                         break;
1382                 case HSMA_REMOVE:
1383                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1384                         /* clear ARCHIVED EXISTS and LOST */
1385                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1386                         is_mh_changed = true;
1387                         break;
1388                 case HSMA_CANCEL:
1389                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1390                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1391                                mdt_obd_name(mdt),
1392                                pgs->hpk_cookie,
1393                                PFID(&pgs->hpk_fid));
1394                         break;
1395                 default:
1396                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1397                                mdt_obd_name(mdt),
1398                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1399                                car->car_hai->hai_action);
1400                         rc = -EINVAL;
1401                         break;
1402                 }
1403         }
1404
1405         /* rc != 0 means error when analysing action, it may come from
1406          * a crasy CT no need to manage DIRTY
1407          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1408          * filled
1409          */
1410         if (rc == 0 && !IS_ERR(obj))
1411                 hsm_set_cl_flags(&cl_flags,
1412                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1413
1414         /* unlock is done later, after layout lock management */
1415         if (is_mh_changed && !IS_ERR(obj))
1416                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1417
1418         /* we give back layout lock only if restore was successful or
1419          * if no retry will be attempted and if object is still alive,
1420          * in other cases we just unlock the object */
1421         if (car->car_hai->hai_action == HSMA_RESTORE) {
1422                 struct cdt_restore_handle       *crh;
1423
1424                 /* restore in data FID done, we swap the layouts
1425                  * only if restore is successful */
1426                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1427                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1428                                               &mh);
1429                         if (rc) {
1430                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1431                                         *status = ARS_FAILED;
1432                                 pgs->hpk_errval = -rc;
1433                         }
1434                 }
1435                 /* we have to retry, so keep layout lock */
1436                 if (*status == ARS_WAITING)
1437                         GOTO(out, rc);
1438
1439                 /* restore special case, need to create ChangeLog record
1440                  * before to give back layout lock to avoid concurrent
1441                  * file updater to post out of order ChangeLog */
1442                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1443                              &car->car_hai->hai_fid);
1444                 need_changelog = false;
1445
1446                 /* give back layout lock */
1447                 mutex_lock(&cdt->cdt_restore_lock);
1448                 crh = mdt_hsm_restore_hdl_find(cdt, &car->car_hai->hai_fid);
1449                 if (crh != NULL)
1450                         list_del(&crh->crh_list);
1451                 mutex_unlock(&cdt->cdt_restore_lock);
1452                 /* Just give back layout lock, we keep the reference
1453                  * which is given back later with the lock for HSM
1454                  * flags.
1455                  * XXX obj may be invalid so we do not pass it. */
1456                 if (crh != NULL)
1457                         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
1458
1459                 if (crh != NULL)
1460                         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
1461         }
1462
1463         GOTO(out, rc);
1464
1465 out:
1466         /* always add a ChangeLog record */
1467         if (need_changelog)
1468                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1469                              &car->car_hai->hai_fid);
1470
1471         if (!IS_ERR(obj))
1472                 mdt_object_put(mti->mti_env, obj);
1473
1474         RETURN(rc);
1475 }
1476
1477 /**
1478  * update status of a request
1479  * \param mti [IN] context
1480  * \param pgs [IN] progress of the copy tool
1481  * \param update_record [IN] update llog record
1482  * \retval 0 success
1483  * \retval -ve failure
1484  */
1485 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1486                                  struct hsm_progress_kernel *pgs,
1487                                  const int update_record)
1488 {
1489         struct mdt_device       *mdt = mti->mti_mdt;
1490         struct coordinator      *cdt = &mdt->mdt_coordinator;
1491         struct cdt_agent_req    *car;
1492         int                      rc = 0;
1493         ENTRY;
1494
1495         /* no coordinator started, so we cannot serve requests */
1496         if (cdt->cdt_state == CDT_STOPPED)
1497                 RETURN(-EAGAIN);
1498
1499         /* first do sanity checks */
1500         car = mdt_cdt_update_request(cdt, pgs);
1501         if (IS_ERR(car)) {
1502                 CERROR("%s: Cannot find running request for cookie %#llx"
1503                        " on fid="DFID"\n",
1504                        mdt_obd_name(mdt),
1505                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1506
1507                 RETURN(PTR_ERR(car));
1508         }
1509
1510         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1511                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1512                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1513                       hsm_copytool_action2name(car->car_hai->hai_action),
1514                       pgs->hpk_flags, pgs->hpk_errval,
1515                       PFID(&car->car_hai->hai_fid),
1516                       PFID(&car->car_hai->hai_dfid));
1517
1518         /* progress is done on FID or data FID depending of the action and
1519          * of the copy progress */
1520         /* for restore progress is used to send back the data FID to cdt */
1521         if (car->car_hai->hai_action == HSMA_RESTORE &&
1522             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1523                 car->car_hai->hai_dfid = pgs->hpk_fid;
1524
1525         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1526              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1527             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1528              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1529                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1530                        " does not match request FID "DFID" nor data FID "
1531                        DFID"\n",
1532                        mdt_obd_name(mdt),
1533                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1534                        PFID(&car->car_hai->hai_fid),
1535                        PFID(&car->car_hai->hai_dfid));
1536                 GOTO(out, rc = -EINVAL);
1537         }
1538
1539         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1540                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1541                        " is not coherent (err=%d and not completed"
1542                        " (flags=%d))\n",
1543                        mdt_obd_name(mdt),
1544                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1545                        hsm_copytool_action2name(car->car_hai->hai_action),
1546                        pgs->hpk_errval, pgs->hpk_flags);
1547                 GOTO(out, rc = -EINVAL);
1548         }
1549
1550         /* now progress is valid */
1551
1552         /* we use a root like ucred */
1553         hsm_init_ucred(mdt_ucred(mti));
1554
1555         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1556                 enum agent_req_status    status;
1557
1558                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1559
1560                 CDEBUG(D_HSM, "%s record: fid="DFID" cookie=%#llx action=%s "
1561                               "status=%s\n",
1562                        update_record ? "Updating" : "Not updating",
1563                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1564                        hsm_copytool_action2name(car->car_hai->hai_action),
1565                        agent_req_status2name(status));
1566
1567                 /* update record first (LU-9075) */
1568                 if (update_record) {
1569                         int rc1;
1570
1571                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1572                                                      &pgs->hpk_cookie, 1,
1573                                                      status);
1574                         if (rc1)
1575                                 CERROR("%s: mdt_agent_record_update() failed,"
1576                                        " rc=%d, cannot update status to %s"
1577                                        " for cookie %#llx\n",
1578                                        mdt_obd_name(mdt), rc1,
1579                                        agent_req_status2name(status),
1580                                        pgs->hpk_cookie);
1581                         rc = (rc != 0 ? rc : rc1);
1582                 }
1583
1584                 /* then remove request from memory list (LU-9075) */
1585                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1586
1587                 /* ct has completed a request, so a slot is available,
1588                  * signal the coordinator to find new work */
1589                 mdt_hsm_cdt_event(cdt);
1590         } else {
1591                 /* if copytool send a progress on a canceled request
1592                  * we inform copytool it should stop
1593                  */
1594                 if (car->car_canceled == 1)
1595                         rc = -ECANCELED;
1596         }
1597         GOTO(out, rc);
1598
1599 out:
1600         /* remove ref got from mdt_cdt_update_request() */
1601         mdt_cdt_put_request(car);
1602
1603         return rc;
1604 }
1605
1606
1607 /**
1608  * data passed to llog_cat_process() callback
1609  * to cancel requests
1610  */
1611 struct hsm_cancel_all_data {
1612         struct mdt_device       *mdt;
1613 };
1614
1615 /**
1616  *  llog_cat_process() callback, used to:
1617  *  - purge all requests
1618  * \param env [IN] environment
1619  * \param llh [IN] llog handle
1620  * \param hdr [IN] llog record
1621  * \param data [IN] cb data = struct hsm_cancel_all_data
1622  * \retval 0 success
1623  * \retval -ve failure
1624  */
1625 static int mdt_cancel_all_cb(const struct lu_env *env,
1626                              struct llog_handle *llh,
1627                              struct llog_rec_hdr *hdr, void *data)
1628 {
1629         struct llog_agent_req_rec       *larr;
1630         struct hsm_cancel_all_data      *hcad;
1631         int                              rc = 0;
1632         ENTRY;
1633
1634         larr = (struct llog_agent_req_rec *)hdr;
1635         hcad = data;
1636         if (larr->arr_status == ARS_WAITING ||
1637             larr->arr_status == ARS_STARTED) {
1638                 larr->arr_status = ARS_CANCELED;
1639                 larr->arr_req_change = cfs_time_current_sec();
1640                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1641         }
1642
1643         RETURN(rc);
1644 }
1645
1646 /**
1647  * cancel all actions
1648  * \param obd [IN] MDT device
1649  */
1650 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1651 {
1652         struct lu_env                    env;
1653         struct lu_context                session;
1654         struct mdt_thread_info          *mti;
1655         struct coordinator              *cdt = &mdt->mdt_coordinator;
1656         struct cdt_agent_req            *car;
1657         struct hsm_action_list          *hal = NULL;
1658         struct hsm_action_item          *hai;
1659         struct hsm_cancel_all_data       hcad;
1660         int                              hal_sz = 0, hal_len, rc;
1661         enum cdt_states                  old_state;
1662         ENTRY;
1663
1664         rc = lu_env_init(&env, LCT_MD_THREAD);
1665         if (rc < 0)
1666                 RETURN(rc);
1667
1668         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1669         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1670         if (rc < 0)
1671                 GOTO(out_env, rc);
1672
1673         lu_context_enter(&session);
1674         env.le_ses = &session;
1675
1676         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1677         LASSERT(mti != NULL);
1678
1679         mti->mti_env = &env;
1680         mti->mti_mdt = mdt;
1681
1682         hsm_init_ucred(mdt_ucred(mti));
1683
1684         /* disable coordinator */
1685         rc = set_cdt_state(cdt, CDT_DISABLE, &old_state);
1686         if (rc)
1687                 RETURN(rc);
1688
1689         /* send cancel to all running requests */
1690         down_read(&cdt->cdt_request_lock);
1691         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1692                 mdt_cdt_get_request(car);
1693                 /* request is not yet removed from list, it will be done
1694                  * when copytool will return progress
1695                  */
1696
1697                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1698                         mdt_cdt_put_request(car);
1699                         continue;
1700                 }
1701
1702                 /* needed size */
1703                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1704                           cfs_size_round(car->car_hai->hai_len);
1705
1706                 if (hal_len > hal_sz && hal_sz > 0) {
1707                         /* not enough room, free old buffer */
1708                         OBD_FREE(hal, hal_sz);
1709                         hal = NULL;
1710                 }
1711
1712                 /* empty buffer, allocate one */
1713                 if (hal == NULL) {
1714                         hal_sz = hal_len;
1715                         OBD_ALLOC(hal, hal_sz);
1716                         if (hal == NULL) {
1717                                 mdt_cdt_put_request(car);
1718                                 up_read(&cdt->cdt_request_lock);
1719                                 GOTO(out_cdt_state, rc = -ENOMEM);
1720                         }
1721                 }
1722
1723                 hal->hal_version = HAL_VERSION;
1724                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1725                                 MTI_NAME_MAXLEN);
1726                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1727                 hal->hal_compound_id = car->car_compound_id;
1728                 hal->hal_archive_id = car->car_archive_id;
1729                 hal->hal_flags = car->car_flags;
1730                 hal->hal_count = 0;
1731
1732                 hai = hai_first(hal);
1733                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1734                 hai->hai_action = HSMA_CANCEL;
1735                 hal->hal_count = 1;
1736
1737                 /* it is possible to safely call mdt_hsm_agent_send()
1738                  * (ie without a deadlock on cdt_request_lock), because the
1739                  * write lock is taken only if we are not in purge mode
1740                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1741                  *   nor mdt_cdt_remove_request())
1742                  */
1743                 /* no conflict with cdt thread because cdt is disable and we
1744                  * have the request lock */
1745                 mdt_hsm_agent_send(mti, hal, 1);
1746
1747                 mdt_cdt_put_request(car);
1748         }
1749         up_read(&cdt->cdt_request_lock);
1750
1751         if (hal != NULL)
1752                 OBD_FREE(hal, hal_sz);
1753
1754         /* cancel all on-disk records */
1755         hcad.mdt = mdt;
1756
1757         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1758                               &hcad, 0, 0, WRITE);
1759 out_cdt_state:
1760         /* Enable coordinator, unless the coordinator was stopping. */
1761         set_cdt_state(cdt, old_state, NULL);
1762         lu_context_exit(&session);
1763         lu_context_fini(&session);
1764 out_env:
1765         lu_env_fini(&env);
1766
1767         RETURN(rc);
1768 }
1769
1770 /**
1771  * check if a request is compatible with file status
1772  * \param hai [IN] request description
1773  * \param archive_id [IN] request archive id
1774  * \param rq_flags [IN] request flags
1775  * \param hsm [IN] file HSM metadata
1776  * \retval boolean
1777  */
1778 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1779                               u32 archive_id, u64 rq_flags,
1780                               const struct md_hsm *hsm)
1781 {
1782         int      is_compat = false;
1783         int      hsm_flags;
1784         ENTRY;
1785
1786         hsm_flags = hsm->mh_flags;
1787         switch (hai->hai_action) {
1788         case HSMA_ARCHIVE:
1789                 if (!(hsm_flags & HS_NOARCHIVE) &&
1790                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1791                         is_compat = true;
1792
1793                 if (hsm_flags & HS_EXISTS &&
1794                     archive_id != 0 &&
1795                     archive_id != hsm->mh_arch_id)
1796                         is_compat = false;
1797
1798                 break;
1799         case HSMA_RESTORE:
1800                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1801                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1802                         is_compat = true;
1803                 break;
1804         case HSMA_REMOVE:
1805                 if (!(hsm_flags & HS_RELEASED) &&
1806                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1807                         is_compat = true;
1808                 break;
1809         case HSMA_CANCEL:
1810                 is_compat = true;
1811                 break;
1812         }
1813         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1814                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1815                       PFID(&hai->hai_fid),
1816                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1817                       hai->hai_extent.offset, hai->hai_extent.length,
1818                       hsm->mh_flags,
1819                       (is_compat ? "compatible" : "uncompatible"));
1820
1821         RETURN(is_compat);
1822 }
1823
1824 /*
1825  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1826  */
1827 static const struct {
1828         __u64            bit;
1829         char            *name;
1830         char            *nickname;
1831 } hsm_policy_names[] = {
1832         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1833         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1834         { 0 },
1835 };
1836
1837 /**
1838  * convert a policy name to a bit
1839  * \param name [IN] policy name
1840  * \retval 0 unknown
1841  * \retval   policy bit
1842  */
1843 static __u64 hsm_policy_str2bit(const char *name)
1844 {
1845         int      i;
1846
1847         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1848                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1849                     strcmp(hsm_policy_names[i].name, name) == 0)
1850                         return hsm_policy_names[i].bit;
1851         return 0;
1852 }
1853
1854 /**
1855  * convert a policy bit field to a string
1856  * \param mask [IN] policy bit field
1857  * \param hexa [IN] print mask before bit names
1858  * \param buffer [OUT] string
1859  * \param count [IN] size of buffer
1860  */
1861 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1862                                 const bool hexa)
1863 {
1864         int      i, j;
1865         __u64    bit;
1866         ENTRY;
1867
1868         if (hexa)
1869                 seq_printf(m, "(%#llx) ", mask);
1870
1871         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1872                 bit = (1ULL << i);
1873
1874                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1875                         if (hsm_policy_names[j].bit == bit)
1876                                 break;
1877                 }
1878                 if (bit & mask)
1879                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1880                 else
1881                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1882         }
1883         /* remove last ' ' */
1884         m->count--;
1885         seq_putc(m, '\n');
1886 }
1887
1888 /* methods to read/write HSM policy flags */
1889 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1890 {
1891         struct mdt_device       *mdt = m->private;
1892         struct coordinator      *cdt = &mdt->mdt_coordinator;
1893         ENTRY;
1894
1895         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1896         RETURN(0);
1897 }
1898
1899 static ssize_t
1900 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1901                          size_t count, loff_t *off)
1902 {
1903         struct seq_file         *m = file->private_data;
1904         struct mdt_device       *mdt = m->private;
1905         struct coordinator      *cdt = &mdt->mdt_coordinator;
1906         char                    *start, *token, sign;
1907         char                    *buf;
1908         __u64                    policy;
1909         __u64                    add_mask, remove_mask, set_mask;
1910         int                      rc;
1911         ENTRY;
1912
1913         if (count + 1 > PAGE_SIZE)
1914                 RETURN(-EINVAL);
1915
1916         OBD_ALLOC(buf, count + 1);
1917         if (buf == NULL)
1918                 RETURN(-ENOMEM);
1919
1920         if (copy_from_user(buf, buffer, count))
1921                 GOTO(out, rc = -EFAULT);
1922
1923         buf[count] = '\0';
1924
1925         start = buf;
1926         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1927                start);
1928
1929         add_mask = remove_mask = set_mask = 0;
1930         do {
1931                 token = strsep(&start, "\n ");
1932                 sign = *token;
1933
1934                 if (sign == '\0')
1935                         continue;
1936
1937                 if (sign == '-' || sign == '+')
1938                         token++;
1939
1940                 policy = hsm_policy_str2bit(token);
1941                 if (policy == 0) {
1942                         CWARN("%s: '%s' is unknown, "
1943                               "supported policies are:\n", mdt_obd_name(mdt),
1944                               token);
1945                         hsm_policy_bit2str(m, 0, false);
1946                         GOTO(out, rc = -EINVAL);
1947                 }
1948                 switch (sign) {
1949                 case '-':
1950                         remove_mask |= policy;
1951                         break;
1952                 case '+':
1953                         add_mask |= policy;
1954                         break;
1955                 default:
1956                         set_mask |= policy;
1957                         break;
1958                 }
1959
1960         } while (start != NULL);
1961
1962         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
1963                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
1964
1965         /* if no sign in all string, it is a clear and set
1966          * if some sign found, all unsigned are converted
1967          * to add
1968          * P1 P2 = set to P1 and P2
1969          * P1 -P2 = add P1 clear P2 same as +P1 -P2
1970          */
1971         if (remove_mask == 0 && add_mask == 0) {
1972                 cdt->cdt_policy = set_mask;
1973         } else {
1974                 cdt->cdt_policy |= set_mask | add_mask;
1975                 cdt->cdt_policy &= ~remove_mask;
1976         }
1977
1978         GOTO(out, rc = count);
1979
1980 out:
1981         OBD_FREE(buf, count + 1);
1982         RETURN(rc);
1983 }
1984 LPROC_SEQ_FOPS(mdt_hsm_policy);
1985
1986 #define GENERATE_PROC_METHOD(VAR)                                       \
1987 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
1988 {                                                                       \
1989         struct mdt_device       *mdt = m->private;                      \
1990         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
1991         ENTRY;                                                          \
1992                                                                         \
1993         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
1994         RETURN(0);                                                      \
1995 }                                                                       \
1996 static ssize_t                                                          \
1997 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
1998                           size_t count, loff_t *off)                    \
1999                                                                         \
2000 {                                                                       \
2001         struct seq_file         *m = file->private_data;                \
2002         struct mdt_device       *mdt = m->private;                      \
2003         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
2004         __s64                    val;                                   \
2005         int                      rc;                                    \
2006         ENTRY;                                                          \
2007                                                                         \
2008         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
2009         if (rc)                                                         \
2010                 RETURN(rc);                                             \
2011         if (val > 0 && val < INT_MAX) {                                 \
2012                 cdt->VAR = val;                                         \
2013                 RETURN(count);                                          \
2014         }                                                               \
2015         RETURN(-EINVAL);                                                \
2016 }                                                                       \
2017
2018 GENERATE_PROC_METHOD(cdt_loop_period)
2019 GENERATE_PROC_METHOD(cdt_grace_delay)
2020 GENERATE_PROC_METHOD(cdt_active_req_timeout)
2021 GENERATE_PROC_METHOD(cdt_max_requests)
2022 GENERATE_PROC_METHOD(cdt_default_archive_id)
2023
2024 /*
2025  * procfs write method for MDT/hsm_control
2026  * proc entry is in mdt directory so data is mdt obd_device pointer
2027  */
2028 #define CDT_ENABLE_CMD   "enabled"
2029 #define CDT_STOP_CMD     "shutdown"
2030 #define CDT_DISABLE_CMD  "disabled"
2031 #define CDT_PURGE_CMD    "purge"
2032 #define CDT_HELP_CMD     "help"
2033 #define CDT_MAX_CMD_LEN  10
2034
2035 ssize_t
2036 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
2037                               size_t count, loff_t *off)
2038 {
2039         struct seq_file         *m = file->private_data;
2040         struct obd_device       *obd = m->private;
2041         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
2042         struct coordinator      *cdt = &(mdt->mdt_coordinator);
2043         int                      rc, usage = 0;
2044         char                     kernbuf[CDT_MAX_CMD_LEN];
2045         ENTRY;
2046
2047         if (count == 0 || count >= sizeof(kernbuf))
2048                 RETURN(-EINVAL);
2049
2050         if (copy_from_user(kernbuf, buffer, count))
2051                 RETURN(-EFAULT);
2052         kernbuf[count] = 0;
2053
2054         if (kernbuf[count - 1] == '\n')
2055                 kernbuf[count - 1] = 0;
2056
2057         rc = 0;
2058         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
2059                 if (cdt->cdt_state == CDT_DISABLE) {
2060                         rc = set_cdt_state(cdt, CDT_RUNNING, NULL);
2061                         mdt_hsm_cdt_event(cdt);
2062                         wake_up(&cdt->cdt_waitq);
2063                 } else {
2064                         rc = mdt_hsm_cdt_start(mdt);
2065                 }
2066         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
2067                 if ((cdt->cdt_state == CDT_STOPPING) ||
2068                     (cdt->cdt_state == CDT_STOPPED)) {
2069                         CERROR("%s: Coordinator already stopped\n",
2070                                mdt_obd_name(mdt));
2071                         rc = -EALREADY;
2072                 } else {
2073                         rc = mdt_hsm_cdt_stop(mdt);
2074                 }
2075         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
2076                 if ((cdt->cdt_state == CDT_STOPPING) ||
2077                     (cdt->cdt_state == CDT_STOPPED)) {
2078                         CERROR("%s: Coordinator is stopped\n",
2079                                mdt_obd_name(mdt));
2080                         rc = -EINVAL;
2081                 } else {
2082                         rc = set_cdt_state(cdt, CDT_DISABLE, NULL);
2083                 }
2084         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
2085                 rc = hsm_cancel_all_actions(mdt);
2086         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
2087                 usage = 1;
2088         } else {
2089                 usage = 1;
2090                 rc = -EINVAL;
2091         }
2092
2093         if (usage == 1)
2094                 CERROR("%s: Valid coordinator control commands are: "
2095                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2096                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2097                        CDT_PURGE_CMD, CDT_HELP_CMD);
2098
2099         if (rc)
2100                 RETURN(rc);
2101
2102         RETURN(count);
2103 }
2104
2105 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
2106 {
2107         struct obd_device       *obd = m->private;
2108         struct coordinator      *cdt;
2109         ENTRY;
2110
2111         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2112
2113         seq_printf(m, "%s\n", cdt_mdt_state2str(cdt->cdt_state));
2114
2115         RETURN(0);
2116 }
2117
2118 static int
2119 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2120 {
2121         bool first = true;
2122         int i;
2123         ENTRY;
2124
2125         for (i = 0; i < 8 * sizeof(mask); i++) {
2126                 if (mask & (1UL << i)) {
2127                         seq_printf(m, "%s%s", first ? "" : " ",
2128                                    hsm_copytool_action2name(i));
2129                         first = false;
2130                 }
2131         }
2132         seq_putc(m, '\n');
2133
2134         RETURN(0);
2135 }
2136
2137 static int
2138 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2139 {
2140         struct mdt_device *mdt = m->private;
2141         struct coordinator *cdt = &mdt->mdt_coordinator;
2142
2143         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2144 }
2145
2146 static int
2147 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2148 {
2149         struct mdt_device *mdt = m->private;
2150         struct coordinator *cdt = &mdt->mdt_coordinator;
2151
2152         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2153 }
2154
2155 static int
2156 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2157 {
2158         struct mdt_device *mdt = m->private;
2159         struct coordinator *cdt = &mdt->mdt_coordinator;
2160
2161         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2162 }
2163
2164 static inline enum hsm_copytool_action
2165 hsm_copytool_name2action(const char *name)
2166 {
2167         if (strcasecmp(name, "NOOP") == 0)
2168                 return HSMA_NONE;
2169         else if (strcasecmp(name, "ARCHIVE") == 0)
2170                 return HSMA_ARCHIVE;
2171         else if (strcasecmp(name, "RESTORE") == 0)
2172                 return HSMA_RESTORE;
2173         else if (strcasecmp(name, "REMOVE") == 0)
2174                 return HSMA_REMOVE;
2175         else if (strcasecmp(name, "CANCEL") == 0)
2176                 return HSMA_CANCEL;
2177         else
2178                 return -1;
2179 }
2180
2181 static ssize_t
2182 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2183                             size_t user_count, __u64 *mask)
2184 {
2185         char *buf, *pos, *name;
2186         size_t buf_size;
2187         __u64 new_mask = 0;
2188         int rc;
2189         ENTRY;
2190
2191         if (!(user_count < 4096))
2192                 RETURN(-ENOMEM);
2193
2194         buf_size = user_count + 1;
2195
2196         OBD_ALLOC(buf, buf_size);
2197         if (buf == NULL)
2198                 RETURN(-ENOMEM);
2199
2200         if (copy_from_user(buf, user_buf, buf_size - 1))
2201                 GOTO(out, rc = -EFAULT);
2202
2203         buf[buf_size - 1] = '\0';
2204
2205         pos = buf;
2206         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2207                 int action;
2208
2209                 if (*name == '\0')
2210                         continue;
2211
2212                 action = hsm_copytool_name2action(name);
2213                 if (action < 0)
2214                         GOTO(out, rc = -EINVAL);
2215
2216                 new_mask |= (1UL << action);
2217         }
2218
2219         *mask = new_mask;
2220         rc = user_count;
2221 out:
2222         OBD_FREE(buf, buf_size);
2223
2224         RETURN(rc);
2225 }
2226
2227 static ssize_t
2228 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2229                                         size_t count, loff_t *off)
2230 {
2231         struct seq_file         *m = file->private_data;
2232         struct mdt_device       *mdt = m->private;
2233         struct coordinator *cdt = &mdt->mdt_coordinator;
2234
2235         return mdt_write_hsm_request_mask(file, buf, count,
2236                                            &cdt->cdt_user_request_mask);
2237 }
2238
2239 static ssize_t
2240 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2241                                         size_t count, loff_t *off)
2242 {
2243         struct seq_file         *m = file->private_data;
2244         struct mdt_device       *mdt = m->private;
2245         struct coordinator      *cdt = &mdt->mdt_coordinator;
2246
2247         return mdt_write_hsm_request_mask(file, buf, count,
2248                                            &cdt->cdt_group_request_mask);
2249 }
2250
2251 static ssize_t
2252 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2253                                         size_t count, loff_t *off)
2254 {
2255         struct seq_file         *m = file->private_data;
2256         struct mdt_device       *mdt = m->private;
2257         struct coordinator      *cdt = &mdt->mdt_coordinator;
2258
2259         return mdt_write_hsm_request_mask(file, buf, count,
2260                                            &cdt->cdt_other_request_mask);
2261 }
2262
2263 static int mdt_hsm_cdt_raolu_seq_show(struct seq_file *m, void *data)
2264 {
2265         struct mdt_device *mdt = m->private;
2266         struct coordinator *cdt = &mdt->mdt_coordinator;
2267         ENTRY;
2268
2269         seq_printf(m, "%d\n", (int)cdt->cdt_remove_archive_on_last_unlink);
2270         RETURN(0);
2271 }
2272
2273 static ssize_t
2274 mdt_hsm_cdt_raolu_seq_write(struct file *file, const char __user *buffer,
2275                             size_t count, loff_t *off)
2276
2277 {
2278         struct seq_file *m = file->private_data;
2279         struct mdt_device *mdt = m->private;
2280         struct coordinator *cdt = &mdt->mdt_coordinator;
2281         __s64 val;
2282         int rc;
2283         ENTRY;
2284
2285         rc = lprocfs_str_to_s64(buffer, count, &val);
2286         if (rc < 0)
2287                 RETURN(rc);
2288
2289         cdt->cdt_remove_archive_on_last_unlink = val;
2290         RETURN(count);
2291 }
2292
2293 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2294 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2295 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2296 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2297 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2298 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2299 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2300 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2301 LPROC_SEQ_FOPS(mdt_hsm_cdt_raolu);
2302
2303 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2304         { .name =       "agents",
2305           .fops =       &mdt_hsm_agent_fops                     },
2306         { .name =       "actions",
2307           .fops =       &mdt_hsm_actions_fops,
2308           .proc_mode =  0444                                    },
2309         { .name =       "default_archive_id",
2310           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2311         { .name =       "grace_delay",
2312           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2313         { .name =       "loop_period",
2314           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2315         { .name =       "max_requests",
2316           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2317         { .name =       "policy",
2318           .fops =       &mdt_hsm_policy_fops                    },
2319         { .name =       "active_request_timeout",
2320           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2321         { .name =       "active_requests",
2322           .fops =       &mdt_hsm_active_requests_fops           },
2323         { .name =       "user_request_mask",
2324           .fops =       &mdt_hsm_user_request_mask_fops,        },
2325         { .name =       "group_request_mask",
2326           .fops =       &mdt_hsm_group_request_mask_fops,       },
2327         { .name =       "other_request_mask",
2328           .fops =       &mdt_hsm_other_request_mask_fops,       },
2329         { .name =       "remove_archive_on_last_unlink",
2330           .fops =       &mdt_hsm_cdt_raolu_fops,                },
2331         { 0 }
2332 };