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